Global exception handling in C++

随声附和 提交于 2019-11-30 20:08:19

I always wrap the outer-most function in a try-catch like this:

int main()
{
   try {
      // start your program/function
      Program program; program.Run();
   }
   catch (std::exception& ex) {
      std::cerr << ex.what() << std::endl;
   }
   catch (...) {
      std::cerr << "Caught unknown exception." << std::endl;
   }
}

This will catch everything. Good exception handling in C++ is not about writing try-catch all over, but to catch where you know how to handle it (like you seem to want to do). In this case the only thing to do is to write the error message to stderr so the user can act on it.

you can use a combination of set_terminate and current_exception()

In C++ the terminate function is called when an exception is uncaught. You can install your own terminate handler with the set_terminate function. The downside is that your terminate handler may never return; it must terminate your program with some operating system primitive. The default is just to call abort()

When an exception is raised, if is not caught at that point, it goes up the hierarchy until it is actually caught. If there is no code to handle the exception the program terminates.
You can run specific code before termination to do cleanup by using your own handlers of set_unexpected or set_terminate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!