How do I use try…catch to catch floating point errors?

后端 未结 4 804
野的像风
野的像风 2020-12-11 02:22

I\'m using c++ in visual studio express to generate random expression trees for use in a genetic algorithm type of program.

Because they are random, the trees often

4条回答
  •  醉梦人生
    2020-12-11 03:08

    Are you sure you want to catch them instead of just ignoring them? Assuming you just want to ignore them:

    See this: http://msdn.microsoft.com/en-us/library/c9676k6h.aspx

    For the _MCW_EM mask, clearing the mask sets the exception, which allows the hardware exception; setting the mask hides the exception.

    So you're going to want to do something like this:

    #include 
    #pragma fenv_access (on)
    
    void main()
    {
        unsigned int fp_control_word;
        unsigned int new_fp_control_word;
    
        _controlfp_s(&fp_control_word, 0, 0);
    
        // Make the new fp env same as the old one,
        // except for the changes we're going to make
        new_fp_control_word = fp_control_word | _EM_INVALID | _EM_DENORMAL | _EM_ZERODIVIDE | _EM_OVERFLOW | _EM_UNDERFLOW | _EM_INEXACT;
        //Update the control word with our changes
        _controlfp_s(&fp_control_word, new_fp_control_word, _MCW_EM)
    
    
    }
    

    Some of the confusion here may be over the use of the word "exception". In C++, that's usually referring to the language built-in exception handling system. Floating point exceptions are a different beast altogether. The exceptions a standard FPU is required to support are all defined in IEEE-754. These happen inside the floating-point unit, which can do different things depending on how the float-point unit's control flags are set up. Usually one of two things happens: 1) The exception is ignored and the FPU sets a flag indicating an error occurred in its status register(s). 2) The exception isn't ignored by the FPU, so instead an interrupt gets generated, and whatever interrupt handler was set up for floating-point errors gets called. Usually this does something nice for you like causing you to break at that line of code in the debugger or generating a core file.

    You can find more on IEE-754 here: http://www.openwatcom.org/ftp/devel/docs/ieee-754.pdf

    Some additional floating-point references: http://docs.sun.com/source/806-3568/ncg_goldberg.html http://floating-point-gui.de/

提交回复
热议问题