Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it OK to throw an exception from a destructor in C++?

Tags:

c++

exception

I know the rule is to NEVER throw one during a destructor, and I understand why. I would not dare do it. But even the C++ Faq Lite says that this rule is good 99% of the time. What is the other 1% that they fail to delve into?

Link to the C++ Faq Lite bullet point on throwing from ~():

like image 861
ApplePieIsGood Avatar asked Dec 24 '08 14:12

ApplePieIsGood


People also ask

Can we throw an exception from the destructor?

The C++ rule is that you must never throw an exception from a destructor that is being called during the "stack unwinding" process of another exception. For example, if someone says throw Foo(), the stack will be unwound so all the stack frames between the throw Foo() and the } catch (Foo e) { will get popped.

When can exceptions be thrown?

Exceptions should be used for exceptional situations outside of the normal logic of a program. In the example program an out of range value is likely to be fairly common and should be dealt with using normal if-else type logic.

What happens to a program when an exception is thrown in its destructor?

If the destructor of an object being destroyed during stack unrolling throws another exception which leaves the destructor, the C++ library will immediately terminate the program by calling the terminate() function.

What happens if an exception is thrown from an object's constructor and object's 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.


1 Answers

Just don't do it. If the stars and planets align in such a way that you find you need to...

Still don't do it.

like image 173
John Sonmez Avatar answered Oct 04 '22 17:10

John Sonmez