【发布时间】:2013-06-19 23:19:06
【问题描述】:
在g++ 和clang++(至少在Linux 中)中,在抛出异常但未捕获(未捕获的异常)后会显示以下典型消息:
terminate called after throwing an instance of 'std::runtime_error'
what(): Bye
例如在:
#include<stdexcept>
int main(){
throw std::runtime_error("Bye");
}
如何在仍然可以完全访问抛出的异常的同时自定义错误消息?
文档(http://www.cplusplus.com/reference/exception/set_unexpected/)提到了set_unexpected(和set_terminate),但我不知道unexpected_handle如何实际访问抛出的异常,例如调用e.what()或其他东西.
注意:这背后的原因是我想定制一个更复杂的异常类层次结构的消息,它比简单的what()有更多的信息,如果这种类型我想显示它抛出异常(但如果抛出简单的std::exception&,则默认与典型相同。
注2:根据目前的两条建议,“通过捕获异常来自定义未捕获的异常”。看起来像代码中的内容。我想知道是否有一种方法可以在不向我编写的 all main() 代码中添加 try-catch 块的情况下做同样的事情。
#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';
}
【问题讨论】:
-
你可能想看看 boost_exception 的东西。否则,您为什么不尝试/捕获 std::exception e 并从那里开始工作?这与 Linux 中的默认设置差不多。
标签: c++ exception-handling terminate