捕获使用块内的异常与使用块外的异常 - 哪个更好?

Kas*_*hif 31 c# c#-3.0

这两段代码之间有什么区别,哪种方法更好.

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


using()
{
    try
    {
         //Do stuff
    }
    catch
    {
        //Handle exception
    }
}
Run Code Online (Sandbox Code Playgroud)

Joe*_*orn 29

存在差异,但它归结为使用块创建自己的try和scope块这一事实.

try
{
    using(IDisposable A = GetDisposable())
    { 
      //Do stuff
    }
}
catch
{
    //Handle exception
    // You do NOT have access to A
}


using(IDisposable A = GetDisposable())  //exception here is uncaught
{
    try
    {
         //Do stuff
    }
    catch
    {
        //Handle exception
        // You DO have access to A
    }
}
Run Code Online (Sandbox Code Playgroud)


Dar*_*rov 7

这些块之间存在差异.在第二种情况下,如果在using()行中抛出异常,则不会捕获异常(例如,实例化IDisposable对象并且构造函数抛出异常).哪一个更好将取决于您的具体需求.


Ada*_*ght 5

是.在第一个中,您正在"使用"的资源将在执行catch块之前被释放.在后来,它将在之后处理.而且,"foo"语句不在catch子句的范围内."使用"块几乎就是语法糖

using (foo)
{
}
Run Code Online (Sandbox Code Playgroud)

try
{
  foo;
}
finally
{
  foo.Dispose();
}
Run Code Online (Sandbox Code Playgroud)

没有上下文,哪种行为"更好"并不明显.