Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my terminate handler never invoked?

I have read that one can call std::set_terminate() to use own function as global exception handler, which catches all unhandled exceptions.

Simplified code of my program:

#include <exception>
#include <stdexcept>
#include <iostream>

void my_terminate_handler()
{
    std::cerr << "Terminate handler" << std::endl;

    std::cin.get();

    std::abort();
}

int main()
{
    std::set_terminate(my_terminate_handler);

    int i = 1;
    i--;

    std::cout << 1/i << std::endl;

    return 0;
}

Why my_terminate_handler() never invoked? Both in VC++ 2013, 2015 RC and gcc++-4.8.

like image 232
vladon Avatar asked Dec 02 '22 14:12

vladon


2 Answers

The terminate handler will be called if the program calls terminate. This can happen for various reasons - including an uncaught exception - but division by zero isn't one of those reasons. That gives undefined behaviour; typically, it raises a signal (not a C++ exception), and you'd need to install a signal handler, not a terminate handler, to catch that.

like image 73
Mike Seymour Avatar answered Dec 19 '22 18:12

Mike Seymour


Because there is no uncaught exception in your code. Add one and it gets executed:

#include <exception>
#include <stdexcept>
#include <iostream>

void my_terminate_handler()
{
    std::cerr << "Terminate handler" << std::endl;
}

int main()
{
    std::set_terminate(my_terminate_handler);

    throw "cake";
}
like image 26
gha.st Avatar answered Dec 19 '22 18:12

gha.st