c++ - 抛出异常实例后调用终止,核心转储
问题描述
我正在检查 C++ 异常并遇到一个错误,我不确定它为什么会给我带来问题:
#include <iostream>
#include <exception>
class err : public std::exception
{
public:
const char* what() const noexcept { return "error"; }
};
void f() throw()
{
throw err();
}
int main()
{
try
{
f();
}
catch (const err& e)
{
std::cout << e.what() << std::endl;
}
}
当我运行它时,我收到以下运行时错误:
terminate called after throwing an instance of 'err'
what(): error
Aborted (core dumped)
如果我将try/catch
逻辑完全移至f()
,即
void f()
{
try
{
throw err();
}
catch (const err& e)
{
std::cout << e.what() << std::endl;
}
}
并且只需从main
(没有 main 中的 try/catch 块)调用它,就不会出现错误。我是否不理解某些东西,因为它与从函数中抛出异常有关?
解决方案
throw()
invoid f() throw()
是动态异常规范,自 c++11 起已弃用。它应该用于列出函数可能抛出的异常。空规范 ( throw()
) 表示您的函数不会抛出任何异常。试图从这样的函数调用中抛出异常std::unexpected
,默认情况下会终止。
由于 c++11 指定函数不能抛出的首选方法是使用noexcept
. 例如void f() noexcept
.
推荐阅读
- javascript - 我可以在不添加任何对象变量的情况下向变量添加 setter 和 getter
- asp.net-web-api - Web API JSON 反序列化转换值问题
- python - 从大量数据库中获取信息的正确方法
- javascript - 获取vue中动态类的“活动”类名
- github - 使用 git repo 中的新内容更新本地文件夹
- python - 作为设置要求的一部分安装预构建轮文件
- javascript - 导入后反应奇怪的代码注入会给出错误消息
- python - 如何在标签内包含标签外的文本。Python
- r - 条件检查 - 稀疏数据
- mysql - 如何在单个语句中运行 set 和 select 查询