在嵌套的using语句中处理

时间:2014-03-03 05:49:53

标签: c#

考虑这个课程:

class Person : IDisposable
{
    public Person(int age)
    {

    }
    public void Dispose()
    {
        Console.WriteLine("Dispose");
    }
}

和这段代码:

using (Person perosn = new Person(0))
{
   using (Person child = new Person(1))
   {
   }
}

运行时,此代码输出在控制台中为两个Dispose

我改变了课程:

class Person : IDisposable
{
    public Person(int age)
    {
        if (age == 1)
        {
            throw new Exception("Person");
        }
    }
    public void Dispose()
    {
        Console.WriteLine("Dispose");
    }
}

我得到例外,两个班都没有处理。

那么为什么当我在child的构造函数中抛出新的异常时,两个类都没有被处理?

3 个答案:

答案 0 :(得分:3)

我没有看到相同的结果:

try {
    using (Person perosn = new Person(0))
    {
        using (Person child = new Person(1))
        {
        }
    }
} catch {
    Console.WriteLine("Caught exception");
}

输出:

Dispose
Caught exception

答案 1 :(得分:3)

引用类型的

using语句转换为

{
    ResourceType resource = expression;
    IDisposable d = (IDisposable)resource;
    try {
        statement;
    }
    finally {
        if (d != null) d.Dispose();
    }
}

如您所见,初始化在try之前执行,因此当构造函数抛出异常时,Dispose不会被调用。这就是为什么你看到只打印了一个Disposed字符串。

检查C#规范中的 8.13 using语句以查看更多内容。

答案 2 :(得分:1)

是否有可能添加catch语句(如Blorgbeard's answer中所示),而只是在Visual Studio中运行您的示例?

在这种情况下,Visual Studio will stop execution at the moment the first exception is thrown,是的,person将不予处理。但是,这是开发环境的“功能”,在部署后不会影响您的程序。

相关问题