【问题标题】:When exactly has an exception been caught?究竟什么时候捕获了异常?
【发布时间】:2014-04-23 20:15:14
【问题描述】:

我得到这个以未捕获的异常终止,即使我认为我已经捕获了异常。这是一些示例代码

#include <iostream>
#include <stdexcept>

void throwing(int x)
{
  if(x) throw std::runtime_error("x non-null");
}

int main()
{
  try {
    throwing(1);
  } catch(std::runtime_error const&ex) {
    std::clog << "error: \"" << ex.what() << '\"' << std::endl;
    std::terminate();
  }
  return 0;
}

产生(在报告错误:“x non-null”之后)所述消息(使用带有std=c++11的clang++)。那么,什么时候准确地 捕获了异常,因此在terminate() 的意义上认为未捕获 没有(再次)报告它?或者,等效地(或不是?):我怎样才能捕获一个异常,报告它的what()terminate() 而不会得到这个简介?

(我可以避免举报what(),只举报terminate(),但我想以我自己的方式举报what()。)

【问题讨论】:

  • 你应该阅读一下terminatecplusplus.com/reference/cstdlib/abort
  • 认为这是因为您在 catch 块中仍然有一个活动异常。解决问题的一种方法是直接调用std::abort() 而不是std::terminate()
  • @Praetorian 那么uncaught是指active吗?那么为什么它会报告 uncaught 异常(而不是 active 异常)?
  • 好吧,根据定义,未捕获的异常是活动的,直到您的程序终止。我在gcc or clang output 中都没有看到任何提及未捕获的异常
  • @Praetorian 1 问题不是未捕获的异常是否处于活动状态,而是活动的异常是否未捕获 . 2 我得到 terminating with uncaught exception of std::runtime_error with clang (v3.3, OS/X 10.9) 和 terminate 在抛出一个实例后调用'std::runtime_error' 与 gcc (4v.9)

标签: c++ exception try-catch terminate


【解决方案1】:

由于没有人对此提供答案,而且我的评论似乎不够清楚或被忽视,我将发布一个完整的答案:

或者,等效地(或不是?):我怎样才能捕获一个异常,报告它的 what() 和 terminate() 而不会得到这个简介?

如果你仔细阅读the reference,你会注意到std::terminate() 默认调用abort(),这会导致程序终止返回一个依赖于平台的不成功终止错误代码给宿主环境。

现在,回答引用的问题:要么使用exit(int status)(这是一个better solution,因为你处理了异常)而不是terminate,或者change 终止处理程序

【讨论】:

    猜你喜欢
    • 2018-10-12
    • 2016-08-10
    • 2021-04-15
    • 2014-09-09
    • 2017-12-11
    • 2023-02-25
    • 2011-11-14
    • 1970-01-01
    • 2015-10-12
    相关资源
    最近更新 更多