Search code examples
c++unhandled-exception

Unhandled Exception Handler in c++


I am working on a C++ library where I want to be able to catch any exceptions that occur that haven't been caught by a try/catch statement.

The only thing I can find while Googling around is a catch(...) block but that wouldn't work, I want the library to catch anything that would normally cause a crash. Like the unhandled exception handler in C#.

It doesn't look like though there is any kind of event handler like this in c++. What I was thinking instead was register a signal handler on things like SIGSEGV AND SIGABRT and then when I receive the signal, handle the crash.

Is this the best way of doing it or is there any other options for doing what I am trying to achieve?


Solution

  • I have managed to find a way to sort of implement this to some degree.

    As @user4581301 pointed out I likely wouldn't be able to do anything in the event of a pointer issue or memory issue that might have caused sigsegv or a sigabrt as if that happens the main app is probably irreversably screwed so wouldn't be able to do anything remotely useful.

    However, in the event that an exception is thrown which isn't caught I have found a way to capture it.

    When my library initialised I do the following:

    if (currentTerminationHandler == nullptr)
        {
            currentTerminationHandler = std::get_terminate();
            std::set_terminate(&unhandledTerminateHandler);
        }
    

    The unhandledTerminateHandler method then uses the boost stacktrace at https://www.boost.org/doc/libs/1_65_1/doc/html/stacktrace.html to return a backtrace that is logged.

    Be aware though when doing this when running inside Visual Studio, VS catches the crash before the terminate handler is triggered and stops the terminate trigger from triggering so to get round this you need to run with ctrl+F5 to avoid it running within VS debugger.