我正在检查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 块),那么就没有错误了。 我不明白一些东西,因为它与从函数中抛出异常有关吗?
void f() throw()
中的throw()
是一个动态异常规范,自 c++11 起已弃用。它应该用于列出函数可能引发的异常。空规范(throw()
)意味着你的函数没有可能抛出的异常。尝试从此类函数中引发异常会调用std::unexpected
默认情况下会终止。
自 c++11 以来,指定函数不能抛出的首选方法是使用noexcept
。例如void f() noexcept
.