Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my program terminate when an exception is thrown by a destructor?

I am not getting why if there is an active exception then if an exception is raised again, it leads to termination of program. Could someone explain?

like image 461
Ashish Avatar asked Dec 11 '09 07:12

Ashish


People also ask

What happens when an exception is thrown in a destructor?

Destructors are only called for the completely constructed objects. When the constructor of an object throws an exception, the destructor for that object is not called.

Does throwing an exception terminate the program?

We can throw either checked or unchecked exceptions. The throws keyword allows the compiler to help you write code that handles this type of error, but it does not prevent the abnormal termination of the program.

Is destructor called when exception is thrown?

When an exception is thrown from a constructor, the object is not considered instantiated, and therefore its destructor will not be called. But all destructors of already successfully constructed base and member objects of the same master object will be called.


2 Answers

What is it suppose to do? It can't "double catch" or anything, nor does it make sense to simply ignore one. The standard specifies that if, during stack unwinding, another exception escapes, then terminate shall be called.

There is more discussion in the C++ FAQ. One "solution" is to wrap your destructor code in a try/catch block, and simply don't let exceptions escape.

Another is to come up with some sort of custom exception chaining scheme. You'd do the above, but instead of ignoring an exception, you would append it to the currently thrown exception, and at the catch site handle both by hand.

The best solution, I think, it to try to remove the exceptional code from your destructor.

like image 60
GManNickG Avatar answered Oct 13 '22 14:10

GManNickG


The reason is simple... if an exception is thrown during exception propagation, then which exception should be propagated? The original exception or the new exception? If the new exception is propagated and then handled, how will the program know that the other exception occurred? Or will the original exception be ignored? This and many other complications lead to the simple rule that only one exception may be propagated at a time, and multiple failures will result in the application being terminated.

like image 38
Michael Aaron Safyan Avatar answered Oct 13 '22 15:10

Michael Aaron Safyan