10

Can i implement global exception handling in C++? My requirement is try...catch block is not used in 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 : )

Matt Joiner
  • 112,946
  • 110
  • 377
  • 526
Deviprasad Das
  • 4,203
  • 7
  • 36
  • 51

5 Answers5

8

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.

Daniel Lidström
  • 9,930
  • 1
  • 27
  • 35
  • 1
    Daniel, there are several kinds of exception which are not caught by catch(...) specially if you are using VC++ which differentiates between structured and unstructured exception handling. – Jaywalker Dec 06 '10 at 14:41
  • But those are not C++ exceptions. (and the equivalent errors in Linux are not caught by a try/catch either) – jalf Dec 06 '10 at 14:47
  • Well, the poster only said he was using C++. There was no mention of any platform-specifics. – Daniel Lidström Dec 06 '10 at 14:47
  • 1
    This is not a global exception handler. For example, this technique does not work when using C++ code from another language. Thus I do not think it answers the question. – user239558 Feb 13 '14 at 12:07
  • @user239558 There was no mention of any other language. – Daniel Lidström Feb 13 '14 at 14:46
  • This is exactly what we want to avoid; having the code you are reasoning about trapped inside an exception statement makes it difficult to reason about it; this leads to creating outer functions which in turn splits your code flow and makes you jump all over your code to see what does what instead of having a nice linear flow. a handler would keep main focusing on doing main things; main should have no idea what an exception is. – Dmytro Nov 29 '16 at 22:53
  • 1
    @Dmitry when is an uncaught exception a "nice linear flow"? Sorry if I misunderstood... – Daniel Lidström Nov 30 '16 at 09:56
  • @DanielLidström I still want to catch it, but I want to move the handler of the exceptions from the main into some other function; eg at beginning of main have some function like "std::handle_all_exceptions_using_this_callback(cb);" where any exception that would occur in main would be handled somewhere in another callback, which can worry about exceptions. – Dmytro Nov 30 '16 at 17:41
  • @Dmitry then see for example https://msdn.microsoft.com/en-us/library/ac9f67ah.aspx – Daniel Lidström Nov 30 '16 at 19:40
  • @23W See https://stackoverflow.com/a/7272147/286406 for help in your case. – Daniel Lidström Oct 05 '17 at 14:00
  • @DanielLidström, Thanks I know about it. I meant this answer can't manage this situation. – 23W Oct 05 '17 at 17:14
6

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

hanshenrik
  • 19,904
  • 4
  • 43
  • 89
  • Thank you @hanshenrik, this is super helpful. It does look like you have a syntax error on that first line. I haven't used set_terminate before so I would appreciate it if you can fix it. – Kelly Stevens Apr 21 '21 at 17:22
  • @KellyStevens no i think it's good, it's called a "lambda function", it requires c++11 or newer (so it won't work with c++03 compilers, for example), check https://wandbox.org/permlink/MTAI7OrWoGRYrbMX – hanshenrik Apr 22 '21 at 07:59
5

you can use a combination of set_terminate and current_exception()

lijie
  • 4,811
  • 22
  • 26
4

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

doron
  • 27,972
  • 12
  • 65
  • 103
0

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

Cratylus
  • 52,998
  • 69
  • 209
  • 339
  • To this and all other answers about set_terminate : if the exception is not handled in the catch block, the process will still terminate. – BЈовић Dec 06 '10 at 13:33