简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM