Floating point exceptions

This is a discussion on Floating point exceptions within the C++ Programming forums, part of the General Programming Boards category; I have this problem: I want to make my program throw a floating point exceptions when performing operations on invalid ...

  1. #1
    Registered User
    Join Date
    Oct 2001
    Posts
    43

    Floating point exceptions

    I have this problem: I want to make my program throw a floating point exceptions when performing operations on invalid floating point numbers:
    e.g.

    double dNAN;
    memset(&dNAN, 0xff, sizeof dNan);//dNan = #NAN
    double dTest = 21/dNAN + 32; //I want exception ot be
    //thrown here!

    Please help me how I can do this. I am using BC++ 5.02 & MSVC++ 6.0, on both I can't achieve this.

  2. #2
    Registered User kitten's Avatar
    Join Date
    Aug 2001
    Posts
    109
    Code:
    // defined MyErrorCode class:
    
    class MyErrorCode
    {
      public:
    
        MyErrorCode(const char* Msg) : ErrorMessage(Msg) {}
    
        void PrintError(void) { cout << MyErrorCode; }
    
      private:
    
        const char* MyErrorCode;
    };
    
    
    try
    {
      // here the operation you want to test.. f.ex:
      if ( error situation ) throw MyErrorCode("Error with division");
    }
    catch (MyErrorCode& e)
    {
      // do whatever you want with e here... f.ex:
      e.PrintError();
    }
    This class takes a pointer to an error message as a parameter and member function can print it for you. This is just a simple example. The class you throw can do anything a class can do. Or you can decide it to do nothing, when it serves as a error identification because every catchable type must be an individual data type.
    Code:
    // a simple error
    
    class SimpleError
    {};
    Making error is human, but for messing things thoroughly it takes a computer

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    43

    Not what I want

    Look, I know how to throw exceptions and how to catch them. What I don't know is how to make compiler turn on floating point exceptions, provided by the hardware. I am absolutely sure for example, that I can make this throw one:
    int i = #NanValue, where #NanValue is a non-valid double expression. This I can achive through _controlfp, or _control87 functions. The problem is that I want the program to throw that in expression of doubles only:
    e.g.
    double dt = 10/#NanValue + 2;

    The problem of course is much more complex: the value is invalidated somewhere in the program, e.g. in destruction of object, that by some reason this value is used and I want to detect that in my program without using external tools (like Bounds Checker, Codeguard, etc.) So this is a extremely simple code that shows what I mean:

    #include <time.h>
    double dStaticValue;

    void PreInit()
    {
    memset(&dStaticValue, 0xff, sizeof dStaticValue);
    }

    void Init()
    {
    dStaticValue = (double)clock();//e.g.
    }

    int main()
    {
    PreInit();
    //not a normal use of the dStaticValue, I want my program
    //to break here while debugging as exception is raised:
    double dShouldCrash = 10*dStaticValue;


    Init();
    //Normal use of dStaticValue
    return 0;
    }

  4. #4
    Unregistered
    Guest
    I work on a software which handles with NANs and infinite doubles. Doesn't matter what it is. When I wanted to know if I operated with such a number a used _finite () or _isnan () test functions in <float.h> header, which could determine it very safely. Any division by 0.0 didn't produced any error nor exception. I want to know if some kind of exception can be invoked automatically by the hardware or something and how can I catch it.

    I believe taht with Kitten's example and _finite () and _isnan () functions you could build up some exception throwing and catching system.

  5. #5
    Registered User
    Join Date
    Oct 2001
    Posts
    43

    Automatic throw of exceptions

    It is not true, that the compiler doesn't throw exception if you divide by 0. It throws if you switch on the right floating point exceptions it will do.
    _controlfp will let you do this, but that is a very private case.

    Maybe I have to tell you more about my specific problem: I am working in a team writing inteligent CAD/CAM system
    www.engview.com
    The project is enourmous: about 128, 000 lines of hard C++ code, with a lot of floating point calculations. So it is absolutely imposible to pass through all of these code and put things like
    ASSERT(_finite(someth));

    So I soon found this problem:
    suppose we have a class DoublePoint:

    struct DoublePoint{ double x, y; };
    Of course it have propper constructors, but doesn't have any constructor.

    Now let us say we have this member function:

    const DoublePoint& GetBeginningOfSth() const { return DoublePoint(beg.x, beg.y); } //We have the needed constructor

    The problem is that a reference to just destroyed object will be returned. Of course I clean up some of these mistakes, but I couldn't be sure there aren't still hidden one. So I decided to do this: in ~DoublePoint fill x & y with NAN, so that when you use some value you would have exception thrown, e.g.:

    DoublePoint bg = GetBeginningOfSth();
    double dDistToOxy = sqrt(sqr(bg.x) + sqr(bg.y));//Here I want exception to be thrown, as both bg.x & bg.y are NAN.

    Is there someone who know that or I will receive another lesson on C++ exception handling, which is good, but doesn't work at all in my case?

  6. #6
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,434
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  7. #7
    Registered User Strider's Avatar
    Join Date
    Aug 2001
    Posts
    149
    Try using the signal function provided in the signal-handling library:
    Code:
    #include <signal.h>
    // or #include <csignal>
    
    // definition:
    signal( int sig, void (__cdecl *func));
    
    /*
    takes an integer signal number and a pointer to the 
    user-defined signal-handling function.
    
    for floating-point exceptions, use SIGFPE for the integer value.
    */
    
    // EXAMPLE
    
    #include <signal.h>
    
    void fpSignal_Handler( int sigVal );
    
    int main()
    {
        signal (SIGFPE, fpSignal_Handler);
    
        // whatever code
    
        // some check for exception
        if ( condition == true )
            raise(SIGFPE);
    
        return 0;
    }
    
    void fpSignal_Handler( int sigVal )
    {
        // handle your exception here
    }
    Hope that helps,
    David
    One Ring to rule them all, One Ring to find them,
    One Ring to bring them all and in the darkness bind them
    In the Land of Mordor where the Shadows lie.

  8. #8
    Registered User
    Join Date
    Oct 2001
    Posts
    43
    What I found was this:

    #include <limits>

    numeric_limts<double>::signaling_NaN() is the value of so called "signaling NaN", the only problem is that MS VC++ 6.0/7.0 doesn't support that as it should. E.g. this code works fine under Borland compilers:

    void main()
    {
    volatile double tdelta = std::numeric_limits<double>::signaling_NaN();
    volatile float delta = 0.05;
    delta = 2/ tdelta +1; //Causes FPE to be raised here automatically
    }

    but not under VC++. So what I decided was to write a class _double with predefined arithmetical operators and conversion operator double with assertions of !_isnan on all of them. I believe this would do. I wrote a test one, but still didn't put it into the "big code"

  9. #9
    Registered User
    Join Date
    Oct 2001
    Posts
    43
    As Damian checked MSVC++ 6.0 is working fine if you switch on floating point exceptions: _controlfp(0, _MCW_EM );
    The problem was in my Beta2 of MSVC 7.0. Any way the class seems to be good solution

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Decimal places on Floating point number
    By manutdfan in forum C Programming
    Replies: 1
    Last Post: 10-29-2006, 11:56 AM
  2. How accurate is the following...
    By emeyer in forum C Programming
    Replies: 22
    Last Post: 12-07-2005, 11:07 AM
  3. floating point question
    By Eric Cheong in forum C Programming
    Replies: 8
    Last Post: 09-10-2004, 10:48 PM
  4. 2 questions about floating point and %
    By ams80 in forum C Programming
    Replies: 2
    Last Post: 08-14-2002, 10:55 AM
  5. Replies: 2
    Last Post: 09-10-2001, 12:00 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21