It is known how to catch the float division-by-zero exception with the usage of
signal(SIGFPE, handler)
but it doesn’t catch integer division-by-zero problem even if I setup control word with
_control87(0, _MCW_EM ); (MS VC 2010)
SubQuestion_1: How to catch integer division-by-zero in C program in Windows without usage of SEH EXCEPTION_INT_DIVIDE_BY_ZERO? (In Unix/Linux this can be done with usage of the standard signal/SIGFPE techinque)
EDIT:
signal is ANSI C signal handling approach.
_control87 is the standard Windows function to set float control word.
Similar question: How to handle all errors, including internal C library errors, uniformly
NOTE (from ISO/IEC 9899:TC2 Annex H.2.2):
“The signed C integer types int, long int, long long int, and the corresponding
unsigned types are compatible with LIA−1. … C’s unsigned integer types are ‘‘modulo’’ in the LIA−1 sense in that overflows or out-of-bounds results silently wrap. An implementation that defines signed integer types as also being modulo need not detect integer overflow, in which case, only integer divide-by-zero need be detected.“
?FINAL SOLUTION:
For Windows: it throws SEH exception. So it can be caught by usage of __try __except.
As possible solution SEH translation could be used to handle SEH exception and translate them to call of needed function. It is not a “natural” way, but it seems that it’s the only way.
For Unix: it could be caught with signal/SIGFPE solution. Or check wiki for FPE_INTDIV solution ( http://rosettacode.org/wiki/Detect_division_by_zero#C ).
As GMan was right about “undefined behaviour” I’m choosing his answer as correct.
Note: It is interesting to check VC\crt\src\winxfltr.c: _XcptActTab array : )
Division by zero leads to undefined behavior, there is no C language construct that can do anything about it. Your best bet is to not divide by zero in the first place, by checking the denominator.
If you want to “catch” (note, C has no exceptions) this error, it will be dependent on your compiler and OS, which you haven’t listed. By the way,
_control87has only to do with floating-point operations, and nothing to do with integer operations.