web analytics

How to Use Try-Catch-Finally Properly in C#?

Options

codeling 1595 - 6639
@2015-12-31 11:55:17

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();
       }
   }
@2015-12-31 11:59:17

Incorrect way

In C#, if you call Cleanup() function like the following way, it will not be executed in case when an asynchronous exception happened inside the ca block

            try
            {
                //...
            }
            catch   
            {       
                //...
            }
            Cleanup();

Correct way

To make sure the Cleanup() function be executed, you have to put it inside the finally block, CLR will ensure it will be executed even in the face of an asynchronous exception .   

            try
            {
                //...
            }
            catch  
            {       
                //...
            }
            finally
            {
                Cleanup();
            }

Here is an example:

public static String GetFileText(String fileName)
{
   String text = "";
   FileInfo fileInfo = new FileInfo(fileName);
   FileStream   fs = null;
   StreamReader sr = null;
   try
   {
      fs = fileInfo.OpenRead();
      sr = new StreamReader(fs);
      text = sr.ReadToEnd();
   }
   catch (IOException)
   {
      throw new FileLoadException("Can't Load this file", fileName);
   }
   finally
   {
      sr.Close();
      fs.Close();
   }
   return text;

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com