Thursday, April 3, 2014

Never throw exception from destructor


In C++, if you get exception in your code, you can handle it using try … catch block. If your code in try block throws exception, it will be caught in catch block.  

In catch block you can either gracefully close, or resume your application depending on severity of exception.

If you do not handle exception in try.. catch block, C++ runtime will call abort() function and application will crash.

So code which can throw exception should be wrapped in try .. catch block. So long so good.

Compiler is good at handling one exception at a time. If your code try to throw more than one exception at a time, application will definitely crash by calling abort() function. (I don’t know why)

And for the same reason, it is considered to be bad practice, to throw exception from destructor.

Let’s see some examples to understand concept.

Here, I am throwing exception from try and it will get caught in catch.  

int main(int argc, char* argv[])
{
     try
     {   
          throw "Exc";
     }
     catch(...)
     {
          std::cout<<"Exception caught"<<std::endl;
     }
     return 0;
}

Output: Exception caught

Now, consider following example, I am throwing exception from destructor. Destructor will get called in two cases, 1) You have created object on heap using new operator and, call delete to destroy object. 2) You have created object on stack, and object goes out of scope.  

class Sample
{
public:
     ~Sample()
     {
          throw "Exc";
     }
};

int main(int argc, char* argv[])
{
     try
     {   
          Sample s;
          throw "ExcMain";
          //other code
     }
     catch(...)
     {
          std::cout<<"Exception caught"<<std::endl;
     }
     return 0;
}

Output : Crash!!!

When “throw ExcMain”, throws exception, stack unwinding starts, and your object “s” goes out of scope,  which calls it’s destructor, which will again throw exception. 

So you have two exceptions at a time. And C++ runtime will call abort().

So never throw exception from destructor.

Please give your suggestion and feedback by leaving comment below article.


Thanks.

3 comments:

  1. Why the program crashes even if i comment out the following
    throw "ExcMain";
    ?

    ReplyDelete
    Replies
    1. The accepted answer for the following SO question is very helpful on this topic
      https://stackoverflow.com/questions/130117/throwing-exceptions-out-of-a-destructor

      Delete
  2. This is my very first time that I am visiting here and I’m truly pleasurable to see everything at one place.
    c++ programming

    ReplyDelete