Try … Catch … Finally – Why do we need it?

Most programmers worth their salt would be well aware of the try / catch construct for catching exceptions.  Most would also be aware that there is a try / catch / finally construct, and that we are advised to perform such operations as closing a file, etc, in the finally block.  I have always been curious why we needed that finally block, however.  Let’s compare following code snippets:

public void Foo(string myfile, string text)
{
    try
    {
        StreamWriter sw = new StreamWriter(myfile, true);
        sw.Write(text);
    }
    catch (Exception e)
    {
        Console.WriteLine("Exception: {0}", e.Message);
    }

    sw.Close();
}

and

public void Foo(string myfile, string text)
{
    try
    {
        StreamWriter sw = new StreamWriter(myfile, true);
        sw.Write(text);
    }
    catch (Exception e)
    {
        Console.WriteLine("Exception: {0}", e.Message);
    }
    finally
    {
        sw.Close();
    }
}

These do the same thing, right?  Yes, we know that the code in the finally block is always executed, but in this case, since the catch block does not return from the method, the StreamWriter will be closed anyway.

How about if we want to return a value, however?  Look at this code:

public string Foo(string myfile)
{
    try
    {
        StreamReader sr = new StreamReader(myfile);
        return sr.ReadLine();
    }
    catch (Exception e)
    {
        return String.Format("Exception: {0}", e.Message);
    }
}

Where do we close the file?  Yes, we could have read the text out of the StreamReader into a temporary variable, closed the file and then returned the variable, but how about this?

public string Foo(string myfile)
{
    try
    {
        StreamReader sr = new StreamReader(myfile);
        return sr.ReadLine();
    }
    catch (Exception e)
    {
        return String.Format("Exception: {0}", e.Message);
    }
    finally
    {
        sr.Close();
    }
}

Remember we said that the code in the finally block will always execute?  Guess what?  That means that it executes even if the method returns beforehand.  Here is the beauty of the finally block – in this code, the StreamReader will be closed whether an exception occurs or not!

Now, to finally try catching up on some sleep….

Advertisements

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