CSharp - Exception finally Block

Introduction

A finally block always executes regardless if there was an exception happened.

finally blocks are typically used for cleanup code.

In the following example, the file opened always gets closed, regardless of whether there is an exception during the file handling.

static void ReadFile()
{
     StreamReader reader = null;    // In System.IO namespace
     try
     {
         reader = File.OpenText ("file.txt");
         if (reader.EndOfStream) return;
         Console.WriteLine (reader.ReadToEnd());
     }
     finally
     {
         if (reader != null) reader.Dispose();
     }
}