Search code examples
c++exceptionlanguage-lawyernullptrrethrow

std::rethrow_exception(nullptr) undefined behavior or bad_exception?


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?


Solution

  • 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.