I encountered some code at work today where an exception is thrown from a destructor.
- You should never throw an exception from a destructor. I point this out because I'm sure if I don't, someone else will.
I am informed that this was a concious design decision and is needed to clean up some data in the case where another failure is encountered. The process of stack-unwinding is being exploited to do the clean up. Under normal circumstances the clean-up process is successful and no exception is thrown. However today I encountered a case where the clean-up failed and an exception is thrown, hence I began to investigate.
The above aside, since this is not a question about code-reviewing code the organization I work for uses, my question is as follows.
What happens if the code path followed as the result of throwing an exception throws another exception?
Since this is an unsual situation I only know of 2 ways this can happen.
The first is the trivial case where an exception is thrown, it is caught by a catch block, and that then throws. This is the same as just throwing an exception which is not caught. There are already some questions about this, for example here. In short,
terminate()
is called.When an exception is thrown, the Stack Unwinding process begins. This process calls destructors of stack allocated objects. Therefore the only other way I know of to cause the throwing of nested exceptions is to throw inside a destructor, in the same manner as I encountered today.
I cannot think of any further possibilities. If there are any I would be interested to hear of them.
Regarding point 2. What happens in this case?