在栈展开时抛出/捕获是否安全?

Is it safe to throw / catch on stack unwind?

本文关键字:是否 安全      更新时间:2023-10-16

Q:在堆栈展开时抛出和捕获异常是否安全,或者应用程序是否在第二次抛出时调用terminate ?

最小的例子:

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)
        {
        }
    }
}

看完这个问题我很好奇。

注意:我知道你可以/应该在析构函数中catch(...),但一般来说在catch块中有try/catch有意义吗-也许在异常(re在我的例子中)的一些函数中调用?

这不是在堆栈展开期间。一旦进入catch块,堆栈就已经展开了。

是的,代码是合法的。看这个问题:嵌套尝试…catch内部c++异常处理程序?

Pubby的答案最好地回答了你所描述的场景。

作为补充,当堆栈展开时,执行的唯一用户代码是析构函数(以及这些析构函数调用的代码)。

如果在此场景中在析构函数中执行 throw(并且不在同一析构函数中捕获异常),则标准指定将调用std::terminate()