C Sharp

Cleaning Up with finally

One sticky issue with exception handling is ensuring that a piece of code is always run regardless of whether an exception is caught. For example, suppose you allocate a resource such as a physical device or a data file. Then suppose that you open this resource and call a method that throws an exception. Regardless of whether your method can continue working with the resource, you still need to deallocate or close that resource. This is when the finally keyword is used, like so: -

using System;
public class ThrowException1App
{
    public static void ThrowException()
    {
        throw new Exception();
    }
    public static void Main()
    {
        try
        {
            Console.WriteLine("try...");
        }
        catch(Exception e)
        {
            Console.WriteLine("catch...");
        }
        finally
        {
            Console.WriteLine("finally");
        }
    }
}

As you can see, the existence of the finally keyword prevents you from having to put this cleanup code both in the catch block and after the try/catch blocks. Now, despite whether an exception is thrown, the code in the finally block will be executed.