Looking on the internet for C++ brainteasers, I found this example:
#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"; // <- crashes here
}
~B()
{
cout << "B::~B()";
}
};
int main(int, char**) {
try
{
cout << "Entering try...catch block" << endl;
A objectA;
B objectB;
cout << "Exiting try...catch block" << endl;
}
catch (const char* ex)
{
cout << ex << endl;
}
return 0;
}
This is what I thought the program would do:
- A::A() will be output to screen when the constructor of objectA is called. Object A is constructed successfully.
- B::B() will be output to screen when the constructor of objectB is called.
- The constructor of B then throws an exception. Object B is not constructed successfully.
- Destructor of objectB is not called as the constructor never completed successfully.
- Destructor of objectA will be called as the object goes out of scope when the try block is exited.
However, when I ran the program, it actually crashed at the line marked with <-. Could anybody explain what exactly was going on at that point?