在栈展开时抛出/捕获是否安全?
Is it safe to throw / catch on stack unwind?
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()
。
相关文章:
- 通过网络、跨平台传递std::变体是否安全
- 在类型和包装器之间reinterpret_cast是否安全<Type>?
- 跨 DLL 边界访问虚拟方法是否安全/可能?
- 静态 constexpr 类成员变量对多线程读取是否安全?
- 在函数结束后使用指向变量的指针是否安全?
- 逐字节删除 void* 是否安全?
- 在 RAII 构造中修改 RVO 值是否安全?
- 线程调用的函数对对象删除是否安全?
- 将对象的字节复制到数组并再次复制回来是否安全
- 使用枚举为数组编制索引是否安全?
- 返回从字符串文本创建的静态string_view是否安全?
- 在cstlib中将#include_next替换为#include是否安全
- 由并发无序映射查找线程调用的函数是否安全?
- 使用 c++ 原子时编写"y=++x"是否安全?
- 从另一个线程发出信号是否安全?
- 从其存储的回调中删除 std::函数是否安全
- 使用 std::vector::swap 方法在C++中交换两个不同的向量是否安全?
- 当我在C++中调用 struce 的只读静态成员时,线程是否安全
- 同时调用 ASIO 对象的 API 是否安全?
- 使用自己的迭代器分配容器是否安全?