【问题标题】:Terminate called after throwing an instance of an exception, core dumped抛出异常实例后调用终止,核心转储
【发布时间】: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。这可能不是你想要的

标签: c++ c++11 exception


【解决方案1】:

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

从 c++11 开始,指定函数不能抛出的首选方法是使用noexcept。例如void f() noexcept

【讨论】:

  • 谢谢!我有一个错误的理解。看起来noexcept(false) 将提供相同的功能并且看起来还没有被弃用
  • @HectorJ noexcept(false) 是大多数函数的默认值,通常不需要提供。我相信析构函数默认是noexcept(true),据我所知,这将是唯一一次noexcept(false) 有意义(尽管不建议这样做)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-03
  • 2011-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多