【发布时间】:2019-05-29 09:46:15
【问题描述】:
我正在处理 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()表示函数不会抛出异常。然后你就可以了。 -
@JesperJuhl:从这样的函数中抛出不是未定义的行为;你打电话给
std::unexpected。这可能不是你想要的。