开发者

Global exception handling in C++

Can i implement global exception handling in C++? My requirement is try...catch block is not used in 开发者_JS百科a piece of code then there should be a global exception handler which will handle all uncaught exception.

Can i achieve it, please give your valuable suggestion : )


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()


i wanted to do the same, here's what i came up with

    std::set_terminate([]() -> void {
        std::cerr << "terminate called after throwing an instance of ";
        try
        {
            std::rethrow_exception(std::current_exception());
        }
        catch (const std::exception &ex)
        {
            std::cerr << typeid(ex).name() << std::endl;
            std::cerr << "  what(): " << ex.what() << std::endl;
        }
        catch (...)
        {
            std::cerr << typeid(std::current_exception()).name() << std::endl;
            std::cerr << " ...something, not an exception, dunno what." << std::endl;
        }
        std::cerr << "errno: " << errno << ": " << std::strerror(errno) << std::endl;
        std::abort();
    });
  • in addition to checking what(), it also checks ernno/std::strerror() - in the future i intend to add stack traces as well through exeinfo/backtrace() too

  • the catch(...) is in case someone threw something other than exception.. for example throw 1; (throw int :| )


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜