c++ - 从 dtor 安全地抛出异常
问题描述
在 C++>=11 中,是否可以从析构函数中安全地抛出异常,即仅在没有异常处于活动状态时才抛出它?
我努力了:
#include <exception>
#include <stdexcept>
#include <stdio.h>
struct foo{
foo();
~foo() noexcept(false);
};
foo::foo() { }
foo::~foo() noexcept(false)
{
if (nullptr==std::current_exception())
throw 2;
}
int main()
{
try{
struct foo f;
#if 1
throw 1;
#endif
}catch(int X){
printf("ex=%d\n", X);
}
}
没有成功。我是否使用了std::current_exception
错误的功能?
我想知道ex=1
该throw 1;
部分是否已启用,ex=2
否则。
目前我得到了terminate called after throwing an instance of 'int'
尽管if
检查,我认为应该阻止第二次抛出,而异常已经处于活动状态。
解决方案
你正在寻找std::uncaught_exceptions
.
std::current_exception
返回指向当前正在处理的异常的指针(即在catch
块中)。
推荐阅读
- vue.js - 计算属性设置器创建超出 Maximus 堆栈
- oracle - 导出 Oracle 模式 ORA 1455
- form-recognizer - GetCustomModelsAsync 未找到 OCR 表单标签工具模型 ID
- python - Python将元组的一部分转换为字符串
- css - 使用 VS2019 Blazor App 和 ASP.NET Core Web 应用程序模板创建的菜单导航栏的定位
- javascript - 你如何在 React Native 中传递对象?
- javascript - 如何获取标签内的单选按钮,该标签位于 div 内?
- django - Django rest 框架 simple-jwt 错误“详细信息”:“没有找到具有给定凭据的活动帐户”
- c# - FtpWebRequest ProtocolViolationException
- python - 将数据框中的值列表附加到新列