Visual C++ / 启用浮点异常后出现奇怪行为(编译器bug?)

9
我正在努力找到一种可靠的方法在Visual Studio(2005或2008)下捕获浮点数异常。默认情况下,在Visual Studio下,浮点数异常不会被捕获,并且它们很难被捕获(主要是因为大多数异常是硬件信号,需要转换为异常)。
以下是我所做的:
- 打开SEH异常处理
(属性/代码生成/启用C++异常:使用SEH异常)
- 使用_controlfp激活浮点数异常
现在我已经捕获了异常(如下面的示例所示,其中包括一个简单的除零异常)。但是,一旦我捕获这个异常,程序似乎就无法挽回地崩溃了(因为简单的浮点初始化以及std::cout都无法工作!)。
我建立了一个简单的演示程序来展示这种相当奇怪的行为。
注意:这种行为在几台计算机上都被复制。
#include "stdafx.h"
#include <math.h>

#include <float.h>
#include <iostream>


using namespace std;


//cf http://www.fortran-2000.com/ArnaudRecipes/CompilerTricks.html#x86_FP
//cf also the "Numerical Recipes" book, which gives the same advice 
    //on how to activate fp exceptions
void TurnOnFloatingExceptions()
{
  unsigned int cw;
  // Note : same result with controlfp
  cw = _control87(0,0) & MCW_EM;
  cw &= ~(_EM_INVALID|_EM_ZERODIVIDE|_EM_OVERFLOW);
  _control87(cw,MCW_EM);

}

//Simple check to ensure that floating points math are still working
void CheckFloats()
{
  try
  {
         // this simple initialization might break 
         //after a float exception!
    double k = 3.; 
    std::cout << "CheckFloatingPointStatus ok : k=" << k << std::endl;
  }  
  catch (...)
  {
    std::cout << " CheckFloatingPointStatus ==> not OK !" << std::endl;
  }
}


void TestFloatDivideByZero()
{
  CheckFloats();
  try
  {
    double a = 5.;
    double b = 0.;
    double c = a / b; //float divide by zero
    std::cout << "c=" << c << std::endl; 
  }
  // this catch will only by active:
  // - if TurnOnFloatingExceptions() is activated 
  // and 
  // - if /EHa options is activated
  // (<=> properties / code generation / Enable C++ Exceptions : Yes with SEH Exceptions)
  catch(...)
  {         
    // Case 1 : if you enable floating points exceptions ((/fp:except)
    // (properties / code generation / Enable floting point exceptions)
    // the following line will not be displayed to the console!
    std::cout <<"Caught unqualified division by zero" << std::endl;
  }
  //Case 2 : if you do not enable floating points exceptions! 
  //the following test will fail! 
  CheckFloats(); 
}


int _tmain(int argc, _TCHAR* argv[])
{
  TurnOnFloatingExceptions();
  TestFloatDivideByZero();
  std::cout << "Press enter to continue";//Beware, this line will not show to the console if you enable floating points exceptions!
  getchar();
}

有人知道如何纠正这种情况吗?非常感谢!

2个回答

11

在捕获浮点数异常时,您需要清除状态字中的FPU异常标志。调用_clearfp()

考虑使用_set_se_translator()编写一个异常过滤器,将硬件异常转换为C++异常。一定要有选择性,只翻译FPU异常。


2
一个重要的注意事项是:_fpreset()将清除浮点状态字并重新初始化浮点数学包,即随后不会抛出异常。为了不禁用随后的异常,可以使用_clearfp()。 - Pascal T.
我遇到了与原问题相同的问题(所以你们两个都加一分)。 - T.E.D.

2

附加信息:如果您在64位Windows上运行32位代码,并使用/arch:SSE2或其他启用SSE2指令集或其超集的选项,则可能需要进行更彻底的重置。

使用Visual Studio 2015(以及VS.2022等较新版本),您需要在SSE2寄存器中生成浮点陷阱后调用_fpreset(),而不仅仅是_clearfp()。如果您在Visual Studio 2013及之前这样做,会出现各种奇怪的问题,因为运行时库会变得混乱。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接