Windows CE: A Quick Guide to Exception Handling

Structured Exception Handling (SEH) is a Microsoft extension to C designed to handle faults gracefully, with the intention that memory and files can be released correctly when execution is unexpectedly terminated.

There are two types of SEH mechanisms:

  • Exception Handlers, or __except blocks, which can respond or dismiss an exception
  • Termination Handlers, or __finally blocks, which are always called whether an exception causes termination or not.

When an exception occurs the stack is unwound and the OS looks for the most recent exception handler. As each layer of the stack is unwound the OS calls any termination handlers which have been written for each function, in the process cleaning up any resources which would have otherwise been left open. This might include closing critical sections, releasing mutexes, or freeing memory.

At each stage of the unwinding process the OS checks the latest functions PDATA structure to find out in an exception handler exists.

OffsetBitsFieldDescription
031-0Begin AddressVirtual address of the corresponding function
47-0Prolog LengthNumber of instructions in the function's prolog
429-8Function LengthNumber of instructions in the function
43032-bit FlagSet if the function uses 32-bit instructions, clear for 16-bit instructions
431Exception FlagSet if an exception handler exists for the function

If an exception handler is flagged to exist or the function length is zero then an additional PDATA_EH structure will precede the function in the .text section. This structure will contain pointers to the exception handler and the handler’s data record.

struct PDATA_EH {
 unsigned int* pHandler; 
 unsigned int* pHandlerData;
};