在vs2005/c++中捕获浮点数异常
vs2005项目的缺省属性是忽略float异常的,要想在代码中捕获float异常按以下方法.
分三步:
1,
//Set the x86 floating-point control word according to what
//exceptions you want to trap.
_clearfp(); //Always call _clearfp before setting the control
//word
//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
//word
//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.
cw &=~(EM_OVERFLOW|EM_UNDERFLOW|EM_ZERODIVIDE|
EM_DENORMAL|EM_INVALID);
//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:
//_controlfp(cwOriginal, MCW_EM);
//exceptions you want to trap.
_clearfp(); //Always call _clearfp before setting the control
//word
//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
//word
//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.
cw &=~(EM_OVERFLOW|EM_UNDERFLOW|EM_ZERODIVIDE|
EM_DENORMAL|EM_INVALID);
//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:
//_controlfp(cwOriginal, MCW_EM);
2,option==>c/c++==>code generation==>Enable c++ Exception改为/EHa
3,
try
{
//Code that may generate a floating-point exception
}
catch(. . .)
{
int fpStatusWord = _clear87();
//You may analyze the bits of the status word.
//Code that does appropriate processing
}
{
//Code that may generate a floating-point exception
}
catch(. . .)
{
int fpStatusWord = _clear87();
//You may analyze the bits of the status word.
//Code that does appropriate processing
}