Question

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)?

Was it helpful?

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?

OTHER TIPS

Pubby's answer best answers the scenario you're describing.

As an addendum, while a stack is unwinding, the only user code that's executed is destructors (and the code those destructors call).

If you do throw in a destructor during this scenario, the standard specifies that std::terminate() will be called.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top