Search code examples
c#try-catchtry-catch-finally

Difference between try{..}catch{...} with finally and without it


What is the difference between code like this:

string path = @"c:\users\public\test.txt";
System.IO.StreamReader file = new System.IO.StreamReader(path);
char[] buffer = new char[10];
try
{
    file.ReadBlock(buffer, index, buffer.Length);
}
catch (System.IO.IOException e)
{
    Console.WriteLine("Error reading from {0}. Message = {1}", path, e.Message);
}

finally
{
    if (file != null)
    {
        file.Close();
    }
}

and this:

string path = @"c:\users\public\test.txt";
System.IO.StreamReader file = new System.IO.StreamReader(path);
char[] buffer = new char[10];
try
{
    file.ReadBlock(buffer, index, buffer.Length);
}
catch (System.IO.IOException e)
{
    Console.WriteLine("Error reading from {0}. Message = {1}", path, e.Message);
}
if (file != null)
{
    file.Close();
}

Is really finally block necessary in this construction. Why Microsoft provided such construction? It seems to be redundant. Isn't it?


Solution

  • Imagine if some other exception occurred that you haven't handled, e.g. an ArgumentOutOfRangeException, or if you want to rethrow the exception or throw a wrapped exception from your catch block:

    1. The first block would ensure that the file is closed regardless of whether or not an exception occurred.

    2. The second block would only close the file if either no exception occurred or an IOException occurred. It does not handle any other cases.

    N.B. The first block also ensures the file is closed if an exception is thrown from inside the catch block itself.