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

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

    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;
    }
    

提交回复
热议问题