Friday, July 15, 2011

The 'Finally' in Try / Catch

When exactly is the finally block called in try/catch statements? If you know, you can correctly predict what gets printed here:

static void Main(string[] args)
{
    AssignToInt(null);
    AssignToInt(new object());
    AssignToInt(1);
}

public static bool AssignToInt(object o)
{
    try
    {
        int i = (int)o;
        Console.WriteLine("{0} assigned OK", i);
        return true;
    }
    catch (NullReferenceException)
    {
        Console.WriteLine("NullReferenceException");
        return false;
    }
    catch (InvalidCastException)
    {
        Console.WriteLine("InvalidCastException");
        return false;
    }
    finally
    {
        Console.WriteLine("Finally...");
    }
}

The finally block is always called after any execution within a try/catch block - regardless of whether an exception was caught or not. Even when a return command is found inside a try or catch block, the CLR will execute the finally block before executing the return command.

The best example of why you would use it is to clean up and close any resources you have left open. Lets say you open a FileStream in your try block - it will need to be closed whether or not an exception occurs. The FileStream.Close() method call should be made inside the finally block.

Therefore the output you get from running the code is:

NullReferenceException
Finally...
InvalidCastException
Finally...
1 assigned OK
Finally...

Further reading:

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.