Dealing with Floating-point Exceptions in MSVC7\8 : Page 3

Learn how to catch floating-point exceptions in C\C++ code.

by Boris Eligulashvili

Jul 13, 2007

Page 3 of 4

Catching the Floating-point Exceptions
The try-except statement is a Microsoft extension to the C and C++ languages that enables 32-bit target applications to gain control when exceptions occur. These exceptions call C, or structured or Win32 exceptions and are identified by an unsigned integer value. Also, they are referenced as "asynchronous." This means that they are secondary to the normal flow of control. According to Intel documentation, in the native mode (not MS DOS), the software exception handler is invoked immediately before the execution of the next floating-point instructionunless it is not one of the non-waiting instructions, the WAIT\FWAIT instruction, or the next MMX™ instruction. The following code snippet shows how to use C exception handling mechanism:

When an exception occurs during the execution of the guarded block or any function called from it, the _except expression is evaluated. Here, GetExceptionCode() retrieves the code that identifies the type of occurred exception. The EvaluateException() calls the filter expression and can be any function that returns an integer value. There are three predefined values that can be returned and that define the program execution pass. The values are defined in the excpt.h file, and they are:

EXCEPTION_EXECUTE_HANDLER: The except block is executed.

EXCEPTION_CONTINUE_SEARCH: The exception handler search continues.

EXCEPTION_CONTINUE_EXECUTION: Execution continues as the exception never occurred.

If a C exception is raised in a C++ program, it can be handled as described above. However, for C++, Microsoft recommends that you use the C++ try-catch exception handling mechanism. This mechanism is fully "synchronous," meaning that it only occurs when it is thrown. The difference between C structured and C++ typed exception handling is that the latter requires the use of the ellipsis handler in order to catch the floating-point exceptions in C++ code. The following code demonstrates this: