Reputation: 9841
#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,
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:
Both the above code throws 2 exception, then why Compiler is biased in destructor's case?
Upvotes: 2
Views: 87
Reputation: 13451
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.
Upvotes: 4