如何自定义未捕获异常终止行为? [英] How to customize uncaught exception termination behavior?
问题描述
在 g ++
和 clang ++
中(至少在Linux中),抛出异常后会显示以下典型消息和不捕获(未捕获异常):
In g++
and clang++
(in Linux at least) the following typical message is shown after an exception is thrown and not catch (uncaught exception):
terminate called after throwing an instance of 'std::runtime_error'
what(): Bye
例如:
#include<stdexcept>
int main(){
throw std::runtime_error("Bye");
}
如何自定义错误消息,同时仍然具有对抛出异常的完全访问权限?
How do I customize the error message while still having full access to the thrown exception?
文档( http:/ /www.cplusplus.com/reference/exception/set_unexpected/ )mentions set_unexpected
(and set_terminate
)但我不知道 unexpected_handle
如何实际访问抛出的异常,例如调用 e.what()
或其他。
The documentation (http://www.cplusplus.com/reference/exception/set_unexpected/) mentions set_unexpected
(and set_terminate
) but I don't know how the unexpected_handle
has actual access to the exception being thrown, for example to call e.what()
or something else.
注意:这背后的原因是我想自定义一个更复杂的异常类层次结构的消息它具有比简单 what()
更多的信息,并且如果抛出此类型异常,我想显示它(但如果一个简单的 std :: exception& ;
Note: The reason behind this is that I want to customize the message for a more complicated exception class hierarchy that has more information than simple what()
, and I want to display it if such type exception is thrown (but if a simple std::exception&
is thrown the default is the same as the typical.
Note2 :根据目前为止的两个建议,通过捕获异常定制未捕获的异常。看起来像下面的代码。我想知道是否有办法做同样没有添加 try-catch
块到全部 main()
我写的代码。
Note2: According to the two suggestions so far, "customize uncaught exceptions by catching the exceptions." Will look like what follows in the code. I was wondering if there is a way to do the same without adding a try-catch
block to all main()
code that I write.
#include<stdexcept>
int main() try{
....
}catch(std::exception& e){
std::clog << "terminate called after throwing an instance of '" << typeid(e) << "'\n"
<< " what(): " << e.what() << '\n'
<< "otherinfo, like current time\n";
}catch(alternative_exception& e){
std::clog << "terminate called after throwing an instance of '" << typeid(e) << "'\n"
<< " what(): " << e.what() << '\n'
<< " where(): " << e.where() << '\n'
<< " how(): " << e.how() << '\n'
<< "othermember(): " << e.othermember() << '\n';
}
推荐答案
您关心, std :: set_terminate()
和 std :: current_exception()
(C ++ 11)应该足以做一些有趣的事情。
Apart from actually catching the exceptions you care about, std::set_terminate()
and std::current_exception()
(C++11) ought to be enough to do something interesting.
这篇关于如何自定义未捕获异常终止行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!