Deviprasad Das
Deviprasad Das

Reputation: 4363

Can you create a global exception handler for uncaught exceptions?

My goal is that when an exception is not caught by a try..catch block, there should be a global exception handler which will handle all uncaught exception.

Upvotes: 11

Views: 18670

Answers (5)

hanshenrik
hanshenrik

Reputation: 21483

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

Upvotes: 8

Daniel Lidstr&#246;m
Daniel Lidstr&#246;m

Reputation: 10260

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.

Upvotes: 8

Cratylus
Cratylus

Reputation: 54074

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

Upvotes: 1

doron
doron

Reputation: 28892

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

Upvotes: 4

lijie
lijie

Reputation: 4871

you can use a combination of set_terminate and current_exception()

Upvotes: 5

Related Questions