捕获所有未处理的 C 异常?

新手上路,请多包涵

是否有某种方法可以捕获未处理的异常(包括那些在 catch 块之外抛出的异常)?

我并不真正关心使用异常完成的所有正常清理工作,只是我可以捕获它,将其写入日志/通知用户并退出程序,因为这些情况下的异常通常是致命的、不可恢复的错误。

就像是:

 global_catch()
{
    MessageBox(NULL,L"Fatal Error", L"A fatal error has occured. Sorry for any inconvience", MB_ICONERROR);
    exit(-1);
}
global_catch(Exception *except)
{
    MessageBox(NULL,L"Fatal Error", except->ToString(), MB_ICONERROR);
    exit(-1);
}

原文由 Fire Lancer 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 616
2 个回答

这可用于捕获意外异常。

 catch (...)
{
    std::cout << "OMG! an unexpected exception has been caught" << std::endl;
}

如果没有 try catch 块,我认为您无法捕获异常,因此请构建您的程序,以便异常代码在 try/catch 的控制下。

原文由 EvilTeach 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果 C++11 可用,则可以使用此方法(参见示例: http ://en.cppreference.com/w/cpp/error/rethrow_exception):

 #include <iostream>
#include <exception>

void onterminate() {
  try {
    auto unknown = std::current_exception();
    if (unknown) {
      std::rethrow_exception(unknown);
    } else {
      std::cerr << "normal termination" << std::endl;
    }
  } catch (const std::exception& e) { // for proper `std::` exceptions
    std::cerr << "unexpected exception: " << e.what() << std::endl;
  } catch (...) { // last resort for things like `throw 1;`
    std::cerr << "unknown exception" << std::endl;
  }
}

int main () {
  std::set_terminate(onterminate); // set custom terminate handler
  // code which may throw...
  return 0;
}

这种方法还允许您为未处理的异常自定义控制台输出:拥有类似这样的东西

unexpected exception: wrong input parameters
Aborted

而不是这个:

 terminate called after throwing an instance of 'std::logic_error'
  what():  wrong input parameters
Aborted

原文由 scrutari 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题