C++ : Catch a divide by zero error

It’s not an exception. It’s an error which is determined at hardware level and is returned back to the operating system, which then notifies your program in some OS-specific way about it (like, by killing the process).

I believe that in such case what happens is not an exception but a signal. If it’s the case: The operating system interrupts your program’s main control flow and calls a signal handler, which – in turn – terminates the operation of your program.

It’s the same type of error which appears when you dereference a null pointer (then your program crashes by SIGSEGV signal, segmentation fault).

You could try to use the functions from <csignal> header to try to provide a custom handler for the SIGFPE signal (it’s for floating point exceptions, but it might be the case that it’s also raised for integer division by zero – I’m really unsure here). You should however note that the signal handling is OS-dependent and MinGW somehow “emulates” the POSIX signals under Windows environment.


Here’s the test on MinGW 4.5, Windows 7:

#include <csignal>
#include <iostream>

using namespace std;

void handler(int a) {
    cout << "Signal " << a << " here!" << endl;
}

int main() {
    signal(SIGFPE, handler);
    int a = 1/0;
}

Output:

Signal 8 here!

And right after executing the signal handler, the system kills the process and displays an error message.

Using this, you can close any resources or log an error after a division by zero or a null pointer dereference… but unlike exceptions that’s NOT a way to control your program’s flow even in exceptional cases. A valid program shouldn’t do that. Catching those signals is only useful for debugging/diagnosing purposes.

(There are some useful signals which are very useful in general in low-level programming and don’t cause your program to be killed right after the handler, but that’s a deep topic).

Leave a Comment