Question

I would like to declare an object in try / catch statement like this:

try {
  Object object(value);
} catch (exception) {
  return 1;
}
object.usingExemple();

G++ tells me that object is not defined in the scope.

I do understand that if try receives an exception object is not created and cannot be used. But shouldn't g++ know that I leave the function if it happens ?

How could I declare an object that throw an exception in the constructor without using new ?

Thanks in advance :)

Was it helpful?

Solution

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top