NOTE: I am using gcc 4.4.7 on redhat linux 6.3. The question in below example is about what GCC does to first exception thrown from A::doSomething()
and NOT about whether exceptions should be thrown from destructor.
In the following code, the function A::doSomething()
exits with 2 logic_error
exceptions.
The second logic_error
from the destructor ~A()
seem to be overwriting the logic_error
from A::doSomething()
.
The output from the program is given below.
My question is what happened to logic_error
thrown by A::doSomething()
. Is there a way to recover it?
#include <iostream>
#include <stdexcept>
#include <sstream>
using namespace std;
class A
{
public:
A(int i):x(i) {};
void doSomething();
~A() {
cout << "Destroying " << x << endl;
stringstream sstr;
sstr << "logic error from destructor of " << x << " ";
throw logic_error(sstr.str());
}
private:
int x;
};
void A::doSomething()
{
A(2);
throw logic_error("from doSomething");
}
int main()
{
A a(1);
try
{
a.doSomething();
}
catch(logic_error & e)
{
cout << e.what() << endl;
}
return 0;
}
Output is:
Destroying 2
logic error from destructor of 2
Destroying 1
terminate called after throwing an instance of 'std::logic_error'
what(): logic error from destructor of 1
Aborted (core dumped)