Welcome to DetlefGrohs.com Sign in | Join | Help

Using Explorations

I noted some odd behavior with the use of the ‘using’ keyword in C#.

Using the following class that implements IDisposable:

   1: namespace UsingExplorations
   2: {
   3: using System;
   4:     public class DisposableClass : IDisposable
   5:     {
   6:         public void Execute()
   7:         {
   8:             throw new NotImplementedException("Exception during execute");
   9:         }
  10:         public void Dispose()
  11:         {
  12:             throw new NotImplementedException("Exception during dispose");
  13:         }
  14:     }
  15: }

Using with no Inner try/catch Block

   1: try
   2: {
   3:     using (DisposableClass disposable_class = new DisposableClass())
   4:     {
   5:         disposable_class.Execute();
   6:     }
   7: }
   8: catch (NotImplementedException e)
   9: {
  10:     Console.WriteLine(e.Message);
  11: }

Produces the following output:

Exception during dispose

Meaning that the exception that was thrown in the Execute method was not caught anywhere.

Using with Inner try/catch Block

   1: try
   2: {
   3:     using (DisposableClass disposable_class = new DisposableClass())
   4:     {
   5:         try
   6:         {
   7:             disposable_class.Execute();
   8:         }
   9:         catch (NotImplementedException e)
  10:         {
  11:             Console.WriteLine(e.Message);
  12:         }
  13:     }
  14: }
  15: catch (NotImplementedException e)
  16: {
  17:     Console.WriteLine(e.Message);
  18: }

Produces the following output:

Exception during execute

Exception during dispose

Meaning that both exceptions were caught. This is the proper pattern for the use of the ‘using’ keyword and proper exception handling.

Summary

It is important to do exception handling inside a using statement to ensure that the exceptions are handled properly. Also, exceptions that occur during the Dispose call when the using statement closes should be caught and handled explicitly if possible.

Published Wednesday, March 04, 2009 11:06 AM by detlef
Filed Under:

Comments

No Comments
Anonymous comments are disabled