2

I have a code snippet where I call rethrow_exception with nullptr as argument. The documentation says the argument should be non-null, but I want to know, if I pass nullptr, is the behavior undefined or known?

I am getting bad_exception everytime. However, this link says the behavior is undefined.

std::string msg;
    try
    {
        std::rethrow_exception(nullptr);
    }
    catch (std::bad_exception &ex)
    {
        msg = ex.what();
    }
    catch (std::exception &ex)
    {
        msg = ex.what();
    }
    catch (...)
    {
        msg = "uncaught exception!";
    }

Anyone, who can comment upon what exactly happens?

Max Langhof
  • 23,383
  • 5
  • 39
  • 72
Ishita
  • 489
  • 5
  • 15
  • 3
    Undefined behaviour can be *anything*. You can't determine that a program *doesn't* have undefined behaviour by inspecting its behaviour. – molbdnilo Dec 11 '19 at 11:54
  • molbdnilo yeah.. I undertsand that, I wanted to know what the C++ standard says. @Max pointed out what I needed. – Ishita Dec 11 '19 at 12:08
  • 1
    @Ishita If you add the [tag:language-lawyer] tag, that will tell people that you would like answers to be supported by quotes from the standard. – Max Langhof Dec 11 '19 at 12:11

1 Answers1

5

It is undefined behavior.

The standard says:

[[noreturn]] void rethrow_exception(exception_ptr p);

Preconditions: p is not a null pointer.

Throws: The exception object to which p refers.

Violating a precondition is UB ([res.on.required]/2). Any behavior you could possibly observe is standard-compliant; the C++ standard places no constraints on what may happen. So don't do it.

Max Langhof
  • 23,383
  • 5
  • 39
  • 72
  • 2
    To add: _20.5.4.11 Requires paragraph [res.on.required] 1 Violation of the preconditions specified in a function’s Requires: paragraph results in undefined behavior unless the function’s Throws: paragraph specifies throwing an exception when the precondition is violated._ (in the draft I have, it's _Requires_ instead of _Preconditions_, but same thing) – ChrisMM Dec 11 '19 at 11:59
  • @ChrisMM Thanks, added. Since it's `Preconditions` and not `Requires`, the following paragraph is actually the one. – Max Langhof Dec 11 '19 at 12:01
  • Must be a newer draft than the one I use (N4659) - it doesn't have `Preconditions`. – ChrisMM Dec 11 '19 at 12:06