首页 > 解决方案 > 抛出异常实例后调用终止,核心转储

问题描述

我正在检查 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 块)调用它,就不会出现错误。我是否不理解某些东西,因为它与从函数中抛出异常有关?

标签: c++c++11exception

解决方案


throw()invoid f() throw()动态异常规范,自 c++11 起已弃用。它应该用于列出函数可能抛出的异常。空规范 ( throw()) 表示您的函数不会抛出任何异常。试图从这样的函数调用中抛出异常std::unexpected,默认情况下会终止。

由于 c++11 指定函数不能抛出的首选方法是使用noexcept. 例如void f() noexcept.


推荐阅读