Enabling the Floating-point Exceptions
By default, floating-point exceptions are not enabled. The following code snippet shows how to enable the x86 (x87 FPU) exceptions that you want to trap:
//Set the x86 floating-point control word according to what
//exceptions you want to trap.
_clearfp(); //Always call _clearfp before setting the control
//Because the second parameter in the following call is 0, it
//only returns the floating-point control word
unsigned int cw = _controlfp(0, 0); //Get the default control
//Set the exception masks off for exceptions that you want to
//trap. When a mask bit is set, the corresponding floating-point
//exception is //blocked from being generating.
//For any bit in the second parameter (mask) that is 1, the
//corresponding bit in the first parameter is used to update
//the control word.
unsigned int cwOriginal = _controlfp(cw, MCW_EM); //Set it.
//MCW_EM is defined in float.h.
//Restore the original value when done:
For example, an exception corresponding to EM_INVALID
can be thrown in the case of 0.0/0.0
. An exception corresponding to EM_OVERFLOW
can be thrown when a variable of the double type is assigned to a variable of the float type and its value is larger in than the largest finite number that can be represented by the float type format. This is demonstrated in the following code:
double d = 1.34E222;
float f = d;
This next code shows you how to enable the SIMD floating-point exceptions that you want to trap:
unsigned long cntrReg;
stmxcsr [cntrReg] //Get MXCSR register
and [cntrReg], 0FFFFFF7Fh//bit 7 - invalid instruction mask
//bit 9 – divide-by-zero mask
//bit 10 - overflow mask
//bit 11 – underflow mask
ldmxcsr [cntrReg] //Load MXCSR register
After you've enabled the exceptions, you may catch them.