Reputation: 1299
I'm facing a situation where I need a try-catch block within a constructor. In particular, the constructor tries to call a function in the try block and if it fails it will call another function to set some values. In both cases, the constructor should create the object properly and in both cases it has to call some other methods before it ends. The situation is as follows:
class A{
A(int i){
try{
setDevice(i);
}
catch(DeviceException& ex){
setDevice (0);
throw ex;
}
otherMethod();
}
}
However, if errors occur in the try block, otherMethod()
is not called because the execution ends within the catch block and I can't use finally like in other languages to do that.
Furthermore, I'm not even sure if, when an exception is raised inside the try block, if the destructor is automatically called and, thus, the object is not properly created.
What do you suggest in this case? Is the object correctly created even if the catch block is reached?
Upvotes: 4
Views: 499
Reputation: 254501
Don't rethrow the exception if you've handled it. Remove throw ex;
to carry on out of the catch
block and complete the constructor normally.
If the exception leaves the constructor, then the object is regarded as not having been initialised. The destructor won't be called; but those for any members and base sub-objects will, and the memory allocated for the object will be freed.
(If you did want to rethrow, that should be just throw;
to avoid making a new copy of the exception object. But you don't want that here either.)
Upvotes: 4