A number of devs don't quite understand the order of operations in structured exception handling.  This leads to some interesting bugs...

Take this snippet of pseudocode, for example:

try {
    EnterCriticalSection();

    try {
        DoSomething()
        RaiseException();
        DoSomethingElse();

    } finally {
        LeaveCriticalSection();
    }
} except(ExceptionFilter()) {
    ReportException();
}

Assuming that ExceptionFilter() returns EXCEPTION_EXECUTE_HANDLER, in what order will these functions be called?


It goes like this:
EnterCriticalSection();
DoSomething();
RaiseException();
ExceptionFilter();
LeaveCriticalSection();
ReportException();

... that is, the exception filter--which is deciding how to deal with the exception--is called before the termination handlers on the stack are executed.

This is pretty obvious if you recall that with a continuable exception, the filter may return EXCEPTION_CONTINUE_EXECUTION, causing execution to resume from the point where the exception was raised.  In that case, DoSomethingElse() would be called, and you wouldn't want to have left the critical section--that'll happen when DoSomethingElse() returns.

The implications get interesting.

If an exception filter is wrapping code the author doesn't control (say, it's making a call into some other dll), it can't know very much about the state of the thread and the system.  The thread might be impersonating, it might be holding locks, who knows?

This limits what the exception filter can do.  For instance, if the thread faulted in the heap, it might be holding the heap lock (since the heap lock's dropped in a termination handler); another thread might be holding the loader lock and attempting to acquire the heap lock, so if the faulting thread blocks on the loader lock, it'll deadlock.

It takes some thought to get this right.  The moral is, unless you fully understand and control the code your exception filter is wrapping, you can't make assumptions about the state of the system in your exception filter.

(Standard Microsoft disclaimer: This posting is provided "AS IS" with no warranties, and confers no rights.)