Maybe exceptions are not supposed to be used as often as I have thought. Since an exception always breaks the scope, you cannot use an object if it's constructors throws exceptions. Consider the following scenario:
Code:
void MyFn() {
MyClass MyObj();
... //A lot of code that may use MyObj, depending on the result of the constructor call
}
Now, if the default constructor can throw an exception, you would have to wrap it in a try block:
Code:
void MyFn() {
try {
MyClass MyObj();
... //A lot of code that uses MyObj
}
catch (ExceptionType exception) {
... //A lot of more code (doesn't use MyObj)
}
}
What happens here is that we will have to write the code two times. One time in the try block (since we want to use MyObj before it goes out of scope), and one time outside of the try block (since we still want to run the code if the constructor fails). The amount of code will almost double.
So my thought was that, if you for example want the thing that caused the exception to be acceptable (i.e. you want the program flow to continue in spite of it, and that not everything just bailes out), maybe you shouldn't use an exception. Maybe one should use some other method instead, like indicating in some way the result of the constructor call (typically a flag would be used), rather than having to leave the scope due to an exception.
What are your thoughts about this?
I also assume that if the constructor throws, the object will never have existed, hence the destructor won't be called.