barcaroller wrote:
I have an object that throws an exception when the constructor fails. I
could construct it inside a try/catch block, but then the object is no
longer visible outside the block.
try
{
classA objA;
}
catch (...)
{
// handle the exception
}
objA.doStuff() // Wrong! Out of scope!
I do not want to move the rest of the program inside the try/catch block.
How do I work around this?
You don't, that's the point. If the construction fails, then it's not a
valid object, so you can't doStuff() with it. You do this:
try
{
classA objA;
objA.doStuff();
}
catch (...)
{
std::cout << "OMG!!! classA constructor failed!!!!" << std::endl;
}
Alternatively, and I don't recommend this method:
std::auto_ptr<classAobjA( NULL );
try
{
objA.reset(new classA);
}
catch(std::bad_alloc&)
{
// new failed
}
catch (...)
{
// classA constructor failed
}
if (objA.get())
objA->doStuff();