Why do I have core dump in this code I see output
Catch
terminate called after throwing an instance of 'std::runtime_error'
what(): ZERO DIV
Aborted (core dumped)
But I expect
Catch
terminate called after throwing an instance of 'std::runtime_error'
what(): ZERO DIV
My code
class Q {
public:
Q(int a, int b) try
: val(b != 0 ? a / b : throw runtime_error("ZERO DIV"))
{
cout << "Q()" << endl;
}
catch(...)
{
cout << "Catch " << endl;
val = nullopt;
}
~Q() {
cout << "~Q()" << endl;
}
private:
optional<int> val;
};
int main() {
Q q = {1, 0};
return 0;
}
I think that the reason of core dump is execution of a / b, but I shouldn't be executed, because b is not zero
The currently handled exception is automatically rethrown if an exception handler in a function-try-block on a constructor doesn't exit via an exception.
That's necessary, because if the constructor has thrown an exception, then it is impossible for the program to continue normally after
Q q = {1, 0};
, since the objectq
can't be properly constructed and usable.You see the core dump because you don't handle the rethrown exception anywhere in
main
, resulting in a call tostd::terminate
, callingstd::abort
which in turn signalsSIGABRT
which is not handled anywhere, so the OS produces a core dump if configured to do so.Also, accessing
val
in the exception handler on the constructor would cause undefined behavior.val
's lifetime hasn't started since it was never initialized.You can't use a function-try-block if you still want the construction to succeed. Avoid using exceptions for that at all and if you must, handle the exceptions in normal try-catch blocks.