try/catch + using, right syntax

Xaqron picture Xaqron · Jan 4, 2011 · Viewed 96k times · Source

Which one:

using (var myObject = new MyClass())
{
   try
   {
      // something here...
   }
   catch(Exception ex)
   {
      // Handle exception
   }
}

OR

try
{
   using (var myObject = new MyClass())
   {
      // something here...
   }
}
catch(Exception ex)
{
   // Handle exception
}

Answer

Jonathan Wood picture Jonathan Wood · Jan 4, 2011

I prefer the second one. May as well trap errors relating to the creation of the object as well.