try/catch + using, right syntax

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
}

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


由于使用块只是try / finally(MSDN)的语法简化,因此我个人会采用以下方法,但我怀疑它与第二个选项有很大不同:

MyClass myObject = null;
try {
  myObject = new MyClass();
  //important stuff
} catch (Exception ex) {
  //handle exception
} finally {
  if(myObject is IDisposable) myObject.Dispose();
}

If your catch statement needs to access the variable declared in a using statement, then inside is your only option.

If your catch statement needs the object referenced in the using before it is disposed, then inside is your only option.

If your catch statement takes an action of unknown duration, like displaying a message to the user, and you would like to dispose of your resources before that happens, then outside is your best option.

Whenever I have a scenerio similar to this, the try-catch block is usually in a different method further up the call stack from the using. It is not typical for a method to know how to handle exceptions that occur within it like this.

So my general recomendation is outside—way outside.

private void saveButton_Click(object sender, EventArgs args)
{
    try
    {
        SaveFile(myFile); // The using statement will appear somewhere in here.
    }
    catch (IOException ex)
    {
        MessageBox.Show(ex.Message);
    }
}
链接地址: http://www.djcxy.com/p/21130.html

上一篇: 如何使用try catch进行异常处理是最佳实践

下一篇: 尝试/ catch +使用,正确的语法