相关疑难解决方法(0)

如何自定义未捕获的异常终止行为?

g++clang++(至少在Linux中),在抛出异常并且没有捕获(未捕获的异常)之后显示以下典型消息:

terminate called after throwing an instance of 'std::runtime_error'
  what():  Bye
Run Code Online (Sandbox Code Playgroud)

例如:

#include<stdexcept>
int main(){
  throw std::runtime_error("Bye");
}
Run Code Online (Sandbox Code Playgroud)

如何在仍具有对抛出异常的完全访问权限的同时自定义错误消息?

文档(http://www.cplusplus.com/reference/exception/set_unexpected/)提到set_unexpected(和set_terminate)但我不知道如何unexpected_handle实际访问被抛出的异常,例如调用e.what()或其他东西.

注意:这背后的原因是我想为更复杂的异常类层次结构自定义消息,该层次结构具有比简单更多的信息what(),并且如果抛出此类型异常,我想显示它(但如果std::exception&抛出一个简单,则默认为与典型相同.

注2:根据到目前为止的两个建议,"通过捕获异常来定制未捕获的异常." 看起来像代码中的内容.我想知道是否有办法在不向我编写的所有代码添加try-catch块的情况下执行相同的操作. main()

#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 …
Run Code Online (Sandbox Code Playgroud)

c++ exception-handling terminate

5
推荐指数
1
解决办法
1817
查看次数

标签 统计

c++ ×1

exception-handling ×1

terminate ×1