14 May 2013

on exception behavior inside using statement block

In another post discussed about prerequisite to use "using" keyword. Now let's discuss more on using statement block and exception inside them on C# .NET.

C# .NET interview question on using statement block:

Will the Dispose() method gets invoked on an exception inside the using statement block?. Let's have a look at "using" keyword program demo code in C# language.

namespace UsingKeywordInterviewQuestion
{
  // Class implemented the IDisposable interface
  public class ClientManager: IDisposable
  {
    public void Dispose()
    {
   Console.WriteLine("Called IDisposable.Dispose() method");
      // Keep the console window open
      Console.ReadLine();
    }
  }
}
class Program
{
 public static void Main(string[] args)
 {
   using (ClientManager clientManager = new ClientManager())
   {
    // Exception occurred inside the using statement block
     throw new Exception();
   }
  }
}
Let's have look at demo code console output:
Unhandled Exception: System.Exception: Exception of type 'System.Exception" was thrown.

at Program.Main(string[] args) in D:\Tutorial\UsingStatement\Program.cs line 13

Called IDiposable.Dispose() method

Analysis of the "using" statement block sample code and its output.

Even when an exception occurred inside the using statement block, the respective class Dispose() method will get invoked.