Design Guideline update: put cleanup code in finally blocks

Another new guideline.. this one sparked a lot of discussion during our internal review, lets see if I cleaned it up well enough or not ;-)

 

           

 

            Do put cleanup code in finally blocks.
Even code that immediately follows a catch() can be interrupted by an asynchronous exceptions (an exception caused by another thread, such as ThreadAbortException. Once the try block is entered, your cleanup code will be guaranteed to run if you put it in a finally block. Notice that the CLR uses a two pass exception model which means that exception filters[1] all the way up the call stack are executed after the catch block but before the finally block.

Incorrect: Cleanup() will not be executed in the face of an asynchronous exception

            try

            {

                //...

            }

            catch //catching *ALL* exceptions and

  // swallowing them

            {

                //...

            }

            //Execute clean up in the exceptional and

//non-exceptional case

            Cleanup();

 

Correct: Cleanup() will be executed even in the face of an asynchronous exception*

            try

            {

                //...

            }

            catch // catching *ALL* exceptions and

// swallowing them

            {

                //...

            }

            finally

            {

                //Execute clean up in the exceptional and

 // non-exceptional case

                Cleanup();

            }

Notice that in this example we catch all exceptions. That is rarely the correct coding practice. It is used here to better illustrate the point of the guideline. Please see section X.y on exception handling.

 

Many methods perform some form of cleanup. All methods that perform cleanup should do so in a finally block. Here is an example:

public void UpdateSet(){
Set mySet = new Set();
try{

foreach (string s in GetValues() ) {
mySet.Add(s);
} ...
}finally{
Set.Close();
}
}


[1] Exception filters are not supported by C#, but supported by VB, IL, etc

* There are some async exceptions such as StackOverflow and Rude Aborts that can cause even code in the finally to be skipped. However these situations are relatively rare and don't change the spirit of this guideline.