Errors and Exceptions
An error can be thought of as a situation that could occur occasionally in known locations. System call errors, for example, should be detected and reported immediately by logic in the code. Thus, programmers normally include an explicit test to see, for instance, whether a file read operation has failed. The ReportError function was developed in Chapter 2 to diagnose and respond to errors.An exception, on the other hand, could occur nearly anywhere, and it is not possible or practical to test for an exception. Division by zero and memory access violations are examples.Nonetheless, the distinction is sometimes blurred. Windows will, optionally, generate exceptions during memory allocation using the HeapAlloc and HeapCreate functions if memory is insufficient. This is described in Chapter 5. Programs can also raise their own exceptions with programmer-defined exception codes using the RaiseException function, as described next.Exception handlers provide a convenient mechanism for exiting from inner blocks or functions under program control without resorting to a goto or longjmp to transfer control. This capability is particularly important if the block has accessed resources, such as open files, memory, or synchronization objects, because the handler can release them. It is also possible to continue program execution after the exception handler, rather than terminate the program. Additionally, a program can restore system state, such as the floating-point mask, on exiting from a block. Many examples use handlers in this way.
User-Generated Exceptions
It is possible to raise an exception at any point during program execution using the RaiseException function. In this way, your program can detect an error and treat it as an exception.
VOID RaiseException (
DWORD dwExceptionCode,
DWORD dwExceptionFlags,
DWORD cArguments,
CONST DWORD *lpArguments)
Parameters
dwExceptionCode is the user-defined code. Do not use bit 28, which is reserved for the system. The error code is encoded in bits 270 (all except the most significant hex digit). Bit 29 should be set to indicate a "customer" (not Microsoft) exception. Bits 3130 encode the severity as follows, where the resulting lead exception code hex digit is shown with bit 29 set.
- 0
Success (lead exception code hex digit is 2). - 1
Informational (lead exception code hex digit is 6). - 2
Warning (lead exception code hex digit is A). - 3
Error (lead exception code hex digit is E).
dwExceptionFlags is normally set to 0, but setting the value to EXCEPTION_NONCONTINUABLE indicates that the filter expression should not generate EXCEPTION_CONTINUE_EXECUTION; doing so will cause an immediate EXCEPTION_NONCONTINUABLE_EXCEPTION exception.Chapter 6, can be used for this purpose.
