Trapping Floating-Point Exceptions in a Win32-based App

Last reviewed: January 9, 1996
Article ID: Q94998
The information in this article applies to:
  • Microsoft Win32 Application Programming Interface (API) included with:

        - Microsoft Windows NT versions 3.1, 3.5, and 3.51
        - Microsoft Windows 95 version 4.0
    

SUMMARY

The _controlfp() function is the portable equivalent to the _control87() function.

To trap floating-point (FP) exceptions via try-except (such as EXCEPTION_FLT_OVERFLOW), insert the following before doing FP operations:

   // Get the default control word.
   int cw = _controlfp( 0,0 );

   // Set the exception masks OFF, turn exceptions on.
   cw &=~(EM_OVERFLOW|EM_UNDERFLOW|EM_INEXACT|EM_ZERODIVIDE|EM_DENORMAL);

   // Set the control word.
   _controlfp( cw, MCW_EM );

This turns on all possible FP exceptions. To trap only particular exceptions, choose only the flags that pertain to the exceptions desired.

Note that any handler for FP errors should have _clearfp() as its first FP instruction.

MORE INFORMATION

By default, Windows NT has all the FP exceptions turned off, and thus computations result in NAN or INFINITY rather than an exception. Note, however, that if an exception occurs and an explicit handler does not exist for it, the default exception handler will terminate the process.

If you want to determine which mask bits are set and which are not during exception handling, you need to use _clearfp() to clear the floating-point exception. This routine returns the existing FP status word, giving the necessary information about the exception. After this, it is safe to query the chip for the state of its control word with _controlfp(). However, as long as an unmasked FP exception is active, most FP instructions will fault, including the fstcw in _controlfp().


Additional reference words: 3.10 3.50 4.00 95
KBCategory: kbprg
KBSubcategory: BseExcept


THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.

Last reviewed: January 9, 1996
© 1998 Microsoft Corporation. All rights reserved. Terms of Use.