Termination Handler - Leave and AbnormalTermination (C)

If you want to prematurely exit a try block without proceeding completely to the closing brace, use the builtin keyword __leave. This keyword causes execution to immediately exit the try block and enter the finally block. There will be no local unwind and no performance penalty. This is ideal for memory management where if memory was not malloc-ed successfully, you can leave the try block. Otherwise, you can continue execution in the try block to manipulate the allocated memory.

In the finally block, you can call a builtin intrinsic function called AbnormalTermination() to tell you whether you exited the try block normally or abnormally.

Here is an example:

   /* Code before try block */               (1)

  __try{
  /* Guarded Body */                        (2)
       someMemory = malloc (100);
       if (someMemory == NULL)
            __leave;
       /* do something with someMemory */
  }

  __finally{
  /* Termination handler */                  (3)
       if (AbnormalTermination())
            printf("Boom!!\n");
       else
            free(someMemory);
  }

  /* Code after the termination handler */   (4)

Code is now executed without a performance hit despite the abnormal exit. When memory is allocated properly, calls to the finally block will execute the memory free function.

There is one case where the Termination handler will not be called. If any threads call the ExitThread, ExitProcess, TerminateThread, or TerminateProcess system functions during the execution of the try block, the system will exit immediately without calling the Termination Handler.



Structured Exception Handling - An Overview
Termination Handler
Termination Handler - Local Unwind