+ 3
What is the Output??
#include <iostream> class A { public: A() {} ~A() { throw 42; } }; int main(int argc, const char * argv[]) { try { A a; throw 32; } catch(int a) { std::cout << a; } }
2 Answers
+ 2
The object of class A is destroyed soon after creation as it had to do nothing, and thus the destructor throws 42. But now, since the catch block was local to main, it could not receive the destructor's throw statement, and no number is printed. However, on running the code, you get a message : "terminate after throwing an instance of 'int'.", which is due to the unhandled throw from the destructor.
+ 2
32 is catched, but before the catch block is executed, 42 is thrown so that your program will terminate due to an uncaught exception of type int with the value 42.
Even if you comment the throw statement out, 42 is not caught.
So don't put throw statements into destructors.