8

Visual Studio (2005 または 2008) で浮動小数点の例外を確実にキャッチする方法を見つけるのに苦労しています。デフォルトでは、Visual Studio では、浮動小数点例外はキャッチされず、キャッチするのが非常に困難です (主に、それらのほとんどがハードウェア シグナルであり、例外に変換する必要があるため)。

これが私がしたことです:
- SEH例外処理を有効にし
ます(プロパティ/コード生成/ C ++例外を有効にする:SEH例外ではい)
- _controlfpを使用して浮動小数点例外を有効にします

私は今、例外をキャッチしています (以下の例に示すように、ゼロ除算の単純な例外です)。ただし、この例外をキャッチするとすぐに、プログラムが取り返しのつかないほど破損しているように見えます (単純な float 初期化と 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();
}

この状況を修正するために何ができるかについて手がかりを持っている人はいますか? よろしくお願いします!

4

2 に答える 2

11

浮動小数点例外をキャッチした場合は、ステータスワードのFPU例外フラグをクリアする必要があります。_clearfp()を呼び出します。

_set_se_translator()を使用して、ハードウェア例外をC++例外に変換する例外フィルターを作成することを検討してください。必ず選択してください。FPU例外のみを変換してください。

于 2010-11-26T18:12:01.340 に答える