Previous Next

Handling Exceptions

The operating system uses structured exception handling to signal certain kinds of errors. A routine called by a driver can raise an exception that the driver must handle.

The system traps the following general kinds of exceptions:

  1. Hardware-defined faults or traps, such as,
  2. System software-defined exceptions, such as,

An access violation is an attempt to perform an operation on a page that is not permitted under the current page protection settings. Access violations occur in the following situations:

A driver handles an exception by enclosing it in a try/except block. For example, the ProbeForWrite routine checks that the driver can actually write to a user-mode buffer. If it cannot, the routine raises a STATUS_ACCESS_VIOLATION exception. The driver can handle this exception as follows:

try {
    ...
    ProbeForWrite(Buffer, BufferSize, BufferAlignment);
    ...note any access (not just the probe which must come first, by the way) to Buffer must also be within a try-except
} except (EXCEPTION_EXECUTE_HANDLER) {
    /* Error handling code. */
    ...
}

Drivers must handle any raised exceptions. An exception that is not handled causes the system to bug check. The driver that causes the exception to be raised must handle it: a lower-level driver cannot rely on a higher-level driver to handle the exception.

Drivers can directly raise an exception, by using the ExRaiseAccessViolation, ExRaiseDatatypeMisalignment, or ExRaiseStatus routines. The driver must handle any exceptions that these routines raise.

The following is a partial list of routines that, at least in certain situations, can raise an exception:

Memory accesses to user-mode buffers can also cause access violations. For more information, see Errors in Referencing User-Space Addresses.

Note that structured exception handling is distinct from C++ exceptions. The kernel does not support C++ exceptions.

For more information on structured exception handling, see the Platform SDK, and the Visual Studio documentation.