Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 481
Kuba Matjanowski Avatar asked Nov 05 '13 22:11

Kuba Matjanowski


1 Answers

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.

like image 75
p.s.w.g Avatar answered Sep 28 '22 02:09

p.s.w.g