#909 – When a finally Block Executes

The purpose of a finally block is to define some code that should always execute, whether or not an exception occurs while executing code in the corresponding try block.

Exactly when a finally block executes depends on several things:

  • If the code in the try block executes without throwing an exception or transferring control elsewhere
    • The finally block executes after the code in the try block
  • If an exception occurs while executing code in the try block ..
    • .. and the exception is caught in a catch block associated with the same try statement — the body of the catch block executes, followed by the body of the finally block
    • .. and the exception is not caught — the body of the finally block executes before the exception propagates back up the call stack
  • If a goto or return statement is encountered in the try block
    • The finally block executes before control is transferred
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #909 – When a finally Block Executes

  1. Pingback: #911 – finally Block Execution When Exception Is Rethrown | 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: