kubisma1
kubisma1

Reputation: 317

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?

Upvotes: 1

Views: 118

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409482

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.

Upvotes: 2

Nathan Monteleone
Nathan Monteleone

Reputation: 5470

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.

Upvotes: 2

Related Questions