Question

#include <iostream>
using namespace std;
class Cls
{
public:
    ~Cls()
    {
        throw "exp";
    }
};

int main()
{
    try
    {
        Cls   c;
        throw "exp";
    }
    catch (...)
    {
        cout << "Why this doesn't call" << endl;
    }
}

When I execute this code, it doesn't goes in catch block. And give following exception, enter image description here

But, when I run this code with little modification, it goes to catch block.

int main()
{
    try
    {
        throw "exp";
        throw "exp";
    }
    catch (...)
    {
        cout << "Why this doesn't call" << endl;
    }
}

Output: enter image description here

Both the above code throws 2 exception, then why Compiler is biased in destructor's case?

Was it helpful?

Solution

In the first case you first throw from the try block and then the stack unwinding throws from Cls's destructor. So you have two exceptions to be handled. C++ handles this situation by calling terminate.

Because of the peculiarity of throwing from destructors, C++11 defines that all destructors are noexcept by default. Then even if there is no other exception to be handled, the exception from a destructor will cause terminate to be called.

The second case is OK because as soon as you throw the first exception try block is left and the exception is handled in the catch block.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top