How do I use try…catch to catch floating point err

2019-01-26 07:43发布

问题:

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 generate: divide by zero, overflow, underflow as well as returning "inf" and other strings. I can write handlers for the strings, but the literature left me baffled about the others. If I understand it correctly, I have to set some flags first?

Advice and/or a pointer to some literature would be appreciated. Edit: the values returned in the double variable are 1.#INF or -1.#IND. I was wrong to call them strings.

回答1:

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 <float.h>
#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/



回答2:

According to http://msdn.microsoft.com/en-us/library/aa289157%28v=vs.71%29.aspx#floapoint_topic8 ,
it seems possible to throw C++ exceptions in MSVC

Create the exceptions classes:

class float_exception : public std::exception {};
class fe_denormal_operand : public float_exception {};
class fe_divide_by_zero : public float_exception {};
class fe_inexact_result : public float_exception {};
class fe_invalid_operation : public float_exception {};
class fe_overflow : public float_exception {};
class fe_stack_check : public float_exception {};
class fe_underflow : public float_exception {};

Map C++ throw to FPU exceptions using structured exception handler

void se_fe_trans_func( unsigned int u, EXCEPTION_POINTERS* pExp )
{
    switch (u)
    {
    case STATUS_FLOAT_DENORMAL_OPERAND:   throw fe_denormal_operand();
    case STATUS_FLOAT_DIVIDE_BY_ZERO:     throw fe_divide_by_zero();
    etc...
    };
}
. . .
_set_se_translator(se_fe_trans_func);

You can then use try catch

try
{
    floating-point code that might throw divide-by-zero 
   or other floating-point exception
}
catch(fe_divide_by_zero)
{
    cout << "fe_divide_by_zero exception detected" << endl;
}
catch(float_exception)
{
    cout << "float_exception exception detected" << endl;
}


回答3:

The C++ runtime environment won't help you the slightest here. You have to perform these checks yourself, explicitly in your code. Unless of course the functions you're calling are doing these checks -- in which case it depends on how they behave in the case of an error.

Let me explain:

double divide(double a, double b) {
    return a / b;  // undefined if b is zero
}

Should be in fact

double divide(double a, double b) {
    if( b == 0 ) {
        // throw, return, flag, ...  you choose how to signal the error
    }
    return a / b;  // b can't possibly be zero here
}

If the code that fails on divide-by-zero and such isn't yours then you'll have to dig deeper to find what it does in the case of a threat for an error. Does it throw? Set a flag? Ask the author and/or read the source.

Here's an example for an exception:

struct bad_value : public std::exception { };

double divide(double a, double b) {
    if( b == 0 ) throw bad_value("Division by zero in divide()");
    return a / b;  // b can't possibly be zero here
}

// elsewhere (possibly in a parallel universe) ...

    try {
        double r1 = divide(5,4);
        double r2 = divide(5,0);
    } catch( bad_value e ) {
        // ...
    }


回答4:

Never tried it, but assuming divide by zero throws an exception, you could just wrap the code in a try/catch like this:

try { // potential divide by zero... } catch(...) { // ... catches ALL exceptions }