Search code examples
delphidelphi-xe6

Disable floating point exceptions during a single function


Can I wrap my Delphi code in the undocumented {$finiteFloat OFF|ON} compiler directive like below to disable floating point exceptions during a function?

{$finiteFloat OFF}
a := 5.0;
b := 0.0;
c := a/b;  // do not raise exception here!
{$finiteFloat ON}

I know I can in the case of constants with {$J} but i don't think {$finiteFloat} can do it because it's scope is global. Can anyone confirm?


Solution

  • This compiler directive applies only to the now defunct .net compiler, which explains why it is not documented. So, this directive has no effect in your program since you are not using the .net compiler. To mask floating point exceptions with your compiler, call SetExceptionMask.

    This article from Hallvard Vassbotn shows the following example code which makes this point:

    {$IFDEF CLR}
      {$FINITEFLOAT OFF}
    {$ELSE}
      Math.SetExceptionMask([exInvalidOp, exDenormalized, exZeroDivide, exOverflow, 
        exUnderflow, exPrecision]);
    {$ENDIF}
    One := 0;
    Two := 42;
    Three := Two / One; // Returns +Inf, no exception raised
    

    Note how Hallvard only used $FINITEFLOAT with the .net compiler. The article also explains why this directive is needed on .net.