Alex Rivera | Logout

Catch exceptions within a using block vs outside the using block - which is better?

Asked 2009-05-26T16:40:49.703
32

Is there any difference between these tow pieces of code & which approach is better.

try
{
    using()
    { 
      //Do stuff
    }
}
catch
{
    //Handle exception
}


using()
{
    try
    {
         //Do stuff
    }
    catch
    {
        //Handle exception
    }
}
Edit
Report

1 Answer

2

As mentioned above, only the first method will catch exceptions in the IDisposable object's initialization, and will have the object in-scope for the catch block.

In addition, the order of operations for the catch and finally blocks will be flipped depending on their nesting. Take the following example:

public class MyDisposable : IDisposable
{
    public void Dispose()
    {
        Console.WriteLine("In Dispose");
    }

    public static void MethodOne()
    {
        Console.WriteLine("Method One");
        using (MyDisposable disposable = new MyDisposable())
        {
            try
            {
                throw new Exception();
            }
            catch (Exception ex)
            {
                Console.WriteLine("In catch");
            }
        }
    }

    public static void MethodTwo()
    {
        Console.WriteLine("Method Two");
        try
        {
            using (MyDisposable disposable = new MyDisposable())
            {
                throw new Exception();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("In catch");
        }
    }

    public static void Main()
    {
        MethodOne();
        MethodTwo();
    }
}

This will print:

Method One
In catch
In Dispose
Method Two
In Dispose
In catch
answered 2013-06-26T01:27:47.140

Your Answer