Hec*_*orJ 12 c++ exception c++11
我正在讨论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;
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行它时,我得到以下运行时错误:
terminate called after throwing an instance of 'err'
what(): error
Aborted (core dumped)
Run Code Online (Sandbox Code Playgroud)
如果我try/catch完全移动逻辑f(),即
void f()
{
try
{
throw err();
}
catch (const err& e)
{
std::cout << e.what() << std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)
只需从中调用它main(没有main中的try/catch块),就没有错误.我不理解某些东西,因为它涉及从函数中抛出异常?
Fra*_*eux 16
的throw()在void f() throw()是一个动态异常规范并且由于C++ 11被弃用.它应该用于列出函数可能抛出的异常.空规范(throw())意味着您的函数不会抛出异常.试图从这样的函数调用抛出异常std::unexpected,默认情况下会终止.
从c ++ 11开始,指定函数不能抛出的首选方法是使用noexcept.例如void f() noexcept.
| 归档时间: |
|
| 查看次数: |
2583 次 |
| 最近记录: |