Why does the following exception thrown from the constructor of class A get caught twice, first by the catch within the constructor itself and second time by the catch in the main function?
Why doesn't it get caught just once by the catch within the constructor?
#include <iostream>
using namespace std;
class E {
public:
const char* error;
E(const char* arg) : error(arg) { }
};
class A {
public:
int i;
A() try : i(0) {
throw E("Exception thrown in A()");
}
catch (E& e) {
cout << e.error << endl;
}
};
int main() {
try {
A x;
}
catch(...)
{
cout << "Exception caught" << endl;
}
}
If I remove the try-catch block in the main function, the program will crash. Here is the output:
Exception thrown in A()
terminate called after throwing an instance of 'E'
zsh: abort (core dumped) ./main
Why does it crash without the try-catch block in the main function?
Function-try-blocks in a constructor cannot prevent exceptions. Once an exception occurs in a constructor, you have no object, and the exception must propagate. The only thing the function-try-block can do is some local clean-up.
Constructors are indeed a very special animal with regards to function-try-blocks.
Cf. C++11 15.3/14:
The currently handled exception is rethrown if control reaches the end of a handler of the function-try-block of a constructor or destructor.
Tl;dr: Do not use function-try-blocks, ever.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With