I have the following code:
#include <iostream>
using namespace std;
class A {
public:
A() { cout << "A::A()" << endl;}
~A() { cout << "A::~A()" << endl; throw "A::exception";}
};
class B {
public:
B() { cout << "B::B()" << endl; throw "B::exception";}
~B() { cout << "B::~B()";}
};
int main() {
try {
cout << "Entering try...catch block" << endl;
A objectA;
B objectB;
cout << "Exiting try...catch block" << endl;
} catch (char const * ex) {
cout << ex << endl;
}
return 0;
}
Now, before stating the question, I would like to point that this code is bad practice (e.g throwing an exception from a constructor will result the object not being fully created, thus the destructor won't be called and it might cause memory leaks or other problems).
Now, The order of the main is this:
Printing
"Entering try...catch block"
.Calling
A
's constructor, printing"A::A()"
Calling
B
's constructor, printing"B::B()"
, and throws exception.The exception was thrown, and the line
"Exiting try...catch block"
will not be printed. The block is exited, soA
's destructor is called.A
's destructor prints"A::~A()"
and throws another exception.
The second exception (in 5) causes the main to throw an exception, before entering the catch
block.
My question is this - is there a way to catch the second exception in the main, without altering the classes A
,B
?
I have tried to surround both the whole try-catch
block and inside the catch
block with another try-catch
block but that didn't work.
Thanks.