Search code examples
c++exceptionstack-unwinding

Is it safe to throw / catch on stack unwind?


Q: Is it safe to throw and catch an exception on stack unwind, or does the application call terminate on the second throw?

minimal example:

void some_function()
{
    try
    {
        // do stuff here that can throw
        throw std::runtime_error("blah");
    } catch(const std::exception& re)
    {
        try // this code could be in some function called from here
        {
            // do something with re here that throws a logical_error
            throw std::logical_error("blah blah"); // does this call terminate?
        } catch(const std::logical_error& le)
        {
        }
    }
}

I got curious after reading this question.

Note: I know you can/should catch(...) in a destructor, but does it make sense in general to have a try/catch in a catch block - maybe in some function called on the exception (re in my example)?


Solution

  • That's not really during stack unwinding. Once a catch block is entered, the stack has already been unwound.

    And yes, that code is legal. See this question: Nested try...catch inside C++ exception handler?