Simple: if your code using object
depends on its creation not raising an exception (it does, since the object is not available if the exception occurs), then it's covered by the same condition as the object's creation. Simply move all code using object
into the try
block:
try {
Object object(value);
object.usingExemple();
} catch (exception) {
return 1;
}
As to why the error itself happens: The block statement in try
introduces a nested scope just like any other pair of braces. All declarations in that scope are local to the scope - so the identifier object
no longer exists outside that scope.
Be careful that my code above is not entirely equivalent to your original code, in that exceptions thrown by usingExample()
will now also be caught (thanks to @immibis for pointing that out). If that is not acceptable for you, you'll have to resort to dynamic allocation:
std::unique_ptr<Object> objectPtr;
try {
objectPtr.reset(new Object(value));
} catch (exception)
return 1;
}
Object &object = *objectPtr;
object.usingExample();
In theory, you could also use placement new
, but I wouldn't recommend that as simply "too weird a solution for the problem at hand:"
alignas(Object) unsigned char objectStorage[sizeof(Object)];
Object *objectPtr;
try {
objectPtr = new (&objectStorage) Object(value);
} catch (exception) {
return 1;
}
try {
Object &object = *objectPtr;
object.usingExample();
} catch (...) {
objectPtr->~Object();
throw;
}