C ++未处理的异常 [英] C++ unhandled exceptions

查看:99
本文介绍了C ++未处理的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果发生未处理的异常,C ++是否提供一种显示视觉内容的方法?

Does C++ offer a way to 'show' something visual if an unhandled exception occurs?

我要做的是制作类似 assert(unhandled exception.msg())如果它确实发生了(如以下示例中所示):

What I want to do is to make something like assert(unhandled exception.msg()) if it actually happens (like in the following sample):

void foo() {
   throw std::exception("Message!");
}

int main() {
 foo();
}

我希望这种代码不会立即终止(因为例外是未处理的),而是显示自定义断言消息(实际上是 Message!)。

推荐答案

标准没有指定任何方法来实际显示未捕获的异常消息。但是,在许多平台上,还是有可能的。在Windows上,可以使用SetUnhandledExceptionFilter并提取C ++异常信息。使用g ++(无论如何都是适当的版本),终止处理程序都可以使用以下代码访问未捕获的异常:

There's no way specified by the standard to actually display the message of the uncaught exception. However, on many platforms, it is possible anyway. On Windows, you can use SetUnhandledExceptionFilter and pull out the C++ exception information. With g++ (appropriate versions of anyway), the terminate handler can access the uncaught exception with code like:

   void terminate_handler()
   {
       try { throw; }
       catch(const std::exception& e) { log(e.what()); }
       catch(...) {}
   }

甚至是g ++默认终止处理程序执行与此类似的操作。您可以使用set_terminate设置终止处理程序。

and indeed g++'s default terminate handler does something similar to this. You can set the terminate handler with set_terminate.

总之,没有通用的C ++方法,但是有些方法取决于您的平台。

IN short, no there's no generic C++ way, but there are ways depending on your platform.

这篇关于C ++未处理的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆