I'm new to C++, and somewhat confused about the following matter:
What happens when a DTOR throws an exception? Is the object still being destroyed?
Thanks in advance.
I'm new to C++, and somewhat confused about the following matter:
What happens when a DTOR throws an exception? Is the object still being destroyed?
Thanks in advance.
And generally: Is it a bad idea?
Yes, a very bad one.
Do not throw exceptions from a destructor. If an exception is thrown after another exception has been thrown, but before that exception has been caught by a catch
handler, your program will be forced to terminate abruptly.
Since destructors are invoked during stack unwinding when an exception is thrown, if one of them throws another exception, that will immediately terminate your program. Not nice.
Avoid throwing exceptions from destructors (or wrap them into try
/catch
blocks so you do not propagate them outside the destructor). Doing so is a bad programming practice.
From Paragraph 15.2/3 of the C++11 Standard:
The process of calling destructors for automatic objects constructed on the path from a try block to the point where an exception is thrown is called “stack unwinding.” If a destructor called during stack unwinding exits with an exception, std::terminate is called (15.5.1). [ Note: So destructors should generally catch exceptions and not let them propagate out of the destructor. —end note ]