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

后端 未结 4 814
野的像风
野的像风 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:15

    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 ) {
            // ...
        }
    

提交回复
热议问题