-1

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

Brian61354270
  • 8,690
  • 4
  • 21
  • 43
mascai
  • 1,373
  • 1
  • 9
  • 30
  • As a side note, what compiler are you using, and do you have warnings enabled? Clang emits _"warning: cannot refer to a non-static member from the handler of a constructor function try block [-Wexceptions]"_ on `val = nullopt;` – Brian61354270 Mar 01 '23 at 23:09
  • 1
    `a / b` is not executed. You are seeing the exception ZERO DIV that you threw – M.M Mar 02 '23 at 02:19
  • I’m voting to close this question because it is simple – mascai Mar 09 '23 at 22:33

1 Answers1

4

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 object q 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 to std::terminate, calling std::abort which in turn signals SIGABRT 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.

user17732522
  • 53,019
  • 2
  • 56
  • 105