The following C# code snippet is used to open a text file and write its contents to the Console. The catch block is used to catch any exception threw during the above operations, and the finally block is used to close the opened file finally, we all know that C# ensures the finally block will be executed in spite of whatever happened in the try and catch block
TextReader reader = null;
try
{
reader = File.OpenText("c:\\test.dat");
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
catch(Exception ex)
{
//handle exception
}
finally
{
reader.Close();
}
Creating a text file named test.dat in the C:\ folder, the code will perform as it is expected, everything looks perfect.
But if you take a close look at the above code, you will find that there is a potential error in it: in case when the file c:\test.dat doesn't exit, the above code will report an error after the finally block is executed:
An unhandled exception of type 'System.NullReferenceException' occurred in ConsoleApplication1.exe
Additional information: Object reference not set to an instance of an object.
The reason is, when the text file c:\test.dat doesn't exit, the reader variable can't be initialized, and a System.IO.FileNotFoundException is threw. In the finally block, the statement reader.Close(); will fail because reader is still a null!.
The Correct Way
To fix the issue, we have to check if the reader variable is null or not before we call its Close() method.
TextReader reader = null;
try
{
reader = File.OpenText("c:\\test.dat");
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
catch(Exception ex)
{
//handle exception
}
finally
{
if (reader != null)
{
reader.Close();
}
}