Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global exception handling in C++

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

like image 641
Deviprasad Das Avatar asked Dec 06 '10 13:12

Deviprasad Das


People also ask

What is global exception handling?

The Global Exception Handler is a type of workflow designed to determine the project's behavior when encountering an execution error. Only one Global Exception Handler can be set per automation project.

What are exception handling in C?

Exception Handling in C++ is a process to handle runtime errors. We perform exception handling so the normal flow of the application can be maintained even after runtime errors. In C++, exception is an event or object which is thrown at runtime. All exceptions are derived from std::exception class.

How many types of exception handling are there in C?

There are two types of exceptions: a)Synchronous, b)Asynchronous (i.e., exceptions which are beyond the program's control, such as disc failure, keyboard interrupts etc.).


1 Answers

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

like image 149
hanshenrik Avatar answered Oct 14 '22 09:10

hanshenrik