Why is my terminate handler never called?

I have read that it is possible to call std::set_terminate()

to use a custom function as a global exception handler that 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 is it my_terminate_handler()

never called? And in VC ++ 2013, 2015 RC and gcC ++ - 4.8.

+3


source to share


2 answers


The completion handler will be called if the program calls terminate

. This can happen for a variety of reasons - including an uncaught exception - but division by zero is not one of those reasons. This gives undefined behavior; typically it raises a signal (not a C ++ exception) and you will need to install a signal handler, not a completion handler, to catch this.



+13


source


Because there is no uncaught exception in your code. Add one and it will be 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";
}

      

+4


source







All Articles