Throwing destructors

Post by Nico Brailovsky @ 2011-09-20 | Permalink | Leave a comment

We already know what happens when you throw from a constructor. Ending up with a half built object is not good, but suppose we do manage to build one correctly. What happens if we throw in a destructor instead? The results are usually much worse, with a very real possibility of having your program terminated. Read on for a brief explanation on the perils of throwing constructors.

So, according to RAII pattern, resource deallocation should occur during the destructor, yet resource freeing is not exempt of possible errors. How would you notify of an error condition?

Yet the worst part is not resource leaking through half destroyed objects, the worst part is having your program call std::abort.

Think of it this way: when an exception is active, the stack is unwind, i.e. the call stack is traversed backwards until a function which can handle the exception is found. And you just can't unwind the stack while unwinding the stack (you'd need a stack of stacks) so the reasonable thing to do is call std::abort.

So, what can you do about it? Go to your favorite jobs posting site and start searching for a PHP position, you'll sleep better at nights.