11

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.

2
  • C++ doesn't dictate any of those operations should throw an exception. They lead to undefined behavior. (Which may crash, or throw an exception, or do nothing, o ...)
    – GManNickG
    Commented May 5, 2010 at 0:39
  • 1
    But C99 and POSIX do specify such things, and provide a numeric exception interface. However, it's a little unclear whether Peter has control over the actual numerics, if he's getting strings out rather than FP infinities. Commented May 5, 2010 at 1:59

4 Answers 4

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;
}
1
  • 3
    This should be the approved answer: it corresponds to the original question (accepted answer basically says "you shouldn't bother" & second says "you can't" (which is incorrect).
    – Deimos
    Commented Oct 7, 2014 at 13:36
7

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/

4
  • 1
    dthorpe: actually, I'm not assuming that it is running on an x86 processor. The MSDN docs explicitly state that _controlfp_s is the new "platform independent" way to do this. I suspect by platform independent they're referring to CPU type, as obviously not all x86 operating systems have this function - as long as he's doing this on a windows platform, he should be OK.
    – George
    Commented May 5, 2010 at 1:03
  • 2
    Also be aware that I've seen libraries warring over the setting of the floating-point control word, each imposing its preference on the other. Almost as bad as printer drivers changing the locale under a program's feed... Commented May 5, 2010 at 10:06
  • 1
    @George: what a great answer! The references were very interesting. You're right, I just want to ignore them. I'll check if the answer is within my acceptable range and throw my own exception if it isn't. The flags are good to know about. Thanks. Commented May 5, 2010 at 10:18
  • 2
    @Peter Stewart: One important thing to keep in mind with your answers is if you get a NaN (Not a Number) as a result, comparison operators don't work the way you think they'll work. For example, one easy way to detect whether a result is a NaN is by checking to see if "f != f" returns true. You might want to check that as well. See this question: stackoverflow.com/questions/570669/…
    – George
    Commented May 6, 2010 at 12:48
2

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 ) {
        // ...
    }
1
  • Thanks. It looks like I'll have to implement my own 'throw's. Commented May 5, 2010 at 10:13
-2

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 }

1
  • 2
    That's wrong, because the C++ runtime environment won't help you here. It won't throw an exception for any reason other than what the programmer specifically asked to throw for. Commented May 5, 2010 at 0:40

Not the answer you're looking for? Browse other questions tagged or ask your own question.