拦截 c++例外情况
所以我的 C++ 程序崩溃了,我得到的错误是:
terminate called after throwing an instance of 'std::length_error'
what(): basic_string::_S_create
Aborted
现在,我最近添加到代码中的是 SIGSEGV 处理程序,因此如果它是分段错误,它将继续打印堆栈跟踪。
如何在 C++ 中为未捕获的(或更类似于不可捕获的)异常创建退出处理程序?
So my c++ program just crashed, and the error I got was:
terminate called after throwing an instance of 'std::length_error'
what(): basic_string::_S_create
Aborted
Now, what I've added recently to my code is a SIGSEGV handler, so if it was a segmentation fault, it would proceed to print the stack trace.
How do I go about making an exit handler for uncaught (or more like uncatchable) exceptions in c++?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用 set_terminate 函数设置终止处理函数:
Use set_terminate function which sets the terminate handler function:
添加到 @vitaut 的答案,如果您使用的是 C++11,您可以在
std::set_terminate
指定的处理程序中检查并获取当前异常。根据 Daniel Krügler,他提到根据下面引用的标准,在调用
std::terminate
期间有一个隐式异常处理程序处于活动状态,这意味着我们可以使用std::current_exception
来检查是否存在是一个活跃的异常并检查它。C++11 标准工作草案 N3242,第 15.3.7 节(强调我的):
窃取 Andrzej 的 C++ 博客,以下是一个示例完成:
Adding to the answer by @vitaut, if you are using C++11 you can check for and get the current exception within the handler specified by
std::set_terminate
.According to Daniel Krügler who refers to the standard quoted below, there is an implicit exception handler active during the call to
std::terminate
, which means that we can usestd::current_exception
to both check whether there is an active exception and also examine it.The C++11 standard working draft N3242, section 15.3.7 (emphasis mine):
Stealing from Andrzej's C++ blog, here is an example of how this can be done:
只需将
try
-catch(...)
放在程序的 to 级别即可。像这样的东西:Just put
try
-catch(...)
at the to level of your program. Something like this:您可以使用
std::set_terminate
< 安装自己的终止处理程序/a>.您可以使用 catch-all 子句
catch (...) {}
捕获所有 C++ 异常。You can install your own terminate handler with
std::set_terminate
.You can catch all C++ exceptions with a catch-all clause
catch (...) {}
.