Search code examples
cfloating-pointfloating-point-exceptions

How to raise a float point exception


guys. I am doing some work around float point operations. The 0.1 is inexact represented by binary float point format. Thus I wrote down this

float i = 0.1f;

and expecting the inexact exception to arise. I turnned on the -fp-trap-all=all option, set fp-mode to be strict and installed SIGFPE signal handler in my code. But nothing happened. Then I tried

float i = 0.1f,j = 0.2f, c;
c = i + j;

still can not catch any exceptions! It drive my crazy.

Sorry to mention that I am using intel c++ compiler on Linux at last.


Solution

  • You have to test for exceptions yourself. The following code works for me:

    #include <stdio.h>
    #include <fenv.h>
    
    #ifndef FE_INEXACT
    #  error No FP Exception handling!
    #endif
    
    int main()
    {
        double a = 4.0;
        a /= 3.0;
    
        if (fetestexcept(FE_INEXACT) & FE_INEXACT)
        {
            printf("Exception occurred\n");
        }
        else
        {
            printf("No exception.\n");
        }
    }
    

    If you replace 4.0 by 3.0, you will not get the exception.

    You can do something similar with double a = 0.0; a = sin(a);.


    Trapping exceptions are only supported conditionally. To check, use the macros described in the documentation:

    #define _GNU_SOURCE
    #include <fenv.h>
    
    #ifndef FE_NOMASK_ENV
    #  warning Cannot raise FP exceptions!
    #else
    #  warning Trapping FP exceptions enabled.
    feenableexcept(FE_INEXACT);
    #endif