Friday, February 11, 2011

Conditions when finally does not execute in a .net try..finally block

Basically I've heard that certain conditions will cause .net to blow past the finally block. Does anyone know what those conditions are?

  • Unless the CLR blows up and goes down with an ExecutingEngineException (I've seen a few in the .net 1.1 days with just the right amount of COM Interop :) .. I think finally should always execute.

    Gishu : Nice.. downvote the first answer that says the same thing as the top-voted one. Care to comment, SO user?
    Andrei Rinea : Just cowards, Gishu. Upvote from me :)
    From Gishu
  • Two possibilities:

    • StackOverflowException
    • ExecutingEngineException

    The finally block will not be executed when there's a StackOverflowException since there's no room on the stack to even execute any more code. It will also not be called when there's an ExecutingEngineException, which is very rare.

    Daniel Fortunov : Perhaps worth noting that ExecutingEngineException may arise from a call to Environment.FailFast()
    From Haacked
  • You can get a situation where the code in the try block causes a SecurityException to be thrown before the try block entered (instead the exception is thrown when the containing method is called (see http://msdn.microsoft.com/en-us/library/fk6t46tz(VS.71).aspx)), in this situation you never even enter the try block so the code in the finally block is never called.

    Other possibilities include StackOverflowException, and ExecutingEngineException.

    From Chris
  • There is also Application.Exit method.

0 comments:

Post a Comment