Search code examples
windowswinapiexceptionseh

Why is SEH considered "asynchronous"?


A few of the articles / answers I read on SEH (Structured Exception Handling) consider it to be 'asynchronous'.

It is my understanding that the whole handling part of these exceptions occurs on the thread that raised them (on the CPU level). Basically, once an exception occurs, the excecution 'jumps' to OS code that iterates on the current thread exception handler list.

So is my understanding correct? What exactly is asynchronous about SEH?


Solution

  • In the synchronous model of exception handling, exceptions are always explicitly thrown; an actual throw statement has to occur in the source code, at a known and clearly defined point in the instruction stream so the compiler has knowledge of when exceptions can occur (which also means it can optimize out exception handling code if it can prove no exceptions can occur).

    SEH is about CPU triggered exceptions, things that the code itself didn't realize could happen, but were raised "out of band" so to speak (they can also be raised explicitly, but that doesn't change what it's designed for). It's asynchronous in that the exception is injected into code that was unaware it could even happen, much in the same way signal handlers can be run in the main thread, interrupting whatever was actually happening at the time the signal was received.

    SEH can be thought of much like temporarily registered signal handlers, where the exceptional conditions are signals, the __try blocks define where the handler is in effect, and the __except and __finally blocks are the handlers if the "signal" is received.