简体   繁体   中英

C++ handling object created in exception

I'm trying to create an object in exception and if it was successfull I want to add that object into the vector. Here's my code:

try{

    CCoord newCoord(input); //I'm parsing the input into several prvt variables

}
catch(...){
    //it failed, just quit
}

//if no error occured, add it to the vector
vCoords.push_back(newCoord);

But I'm not able to access the object outside of try block. Any solution, please?

You can't access an object outside it's scope. Best thing to do is just move the push_back inside the try block (otherwise you'll have to either default construct it above the block or make a pointer and dynamically allocate inside the block).

Here's the better way to do it:

try{

    CCoord newCoord(input); //I'm parsing the input into several prvt variables


    //if no error occured, add it to the vector
    vCoords.push_back(newCoord);
}
catch(...){
    //it failed, just quit
}

Note the comment "if no error occurred, add it to the vector" is still true -- if the CCoord constructor throws an exception it'll jump over the push_back to the catch block.

The object doesn't exist outside the try block. You have to add it inside the block.

A try block is just like any other block, it adds a new scope, and everything declared within that scope is local to that scope.

Besides, if it wasn't local in that block, what if an exception was thrown and caught, but the exception-handler didn't exit, then the object might have been only partially constructed, if at all, so using it after the try-catch would have been undefined behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM