如何捕捉使用块与.NET 2.0中的异常? [英] How to Catch an exception in a using block with .NET 2.0?

查看:151
本文介绍了如何捕捉使用块与.NET 2.0中的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想利用using块越来越多的这些日子,我有一个对象实现IDisposable但有一件事我还没有想出是如何捕获异常,因为我会在一个正常的try / catch /终于...任何code样品给我指出了正确的方向?

I'm trying to leverage the using block more and more these days when I have an object that implements IDisposable but one thing I have not figured out is how to catch an exception as I would in a normal try/catch/finally ... any code samples to point me in the right direction?

编辑:此问题已通过回复看完之后修改。这是如何在使用块抛出一个异常,.NET 2.0?但实际上,我是在寻找一种方式来捕获这些异常的使用块内。

The question was modified after reading through the replies. It was "How to Throw an exception in a using block with .NET 2.0?" but I was actually looking for a way to catch these exceptions inside a using block.

我在寻找更详细的滚动使用块在我自己的追赶块。

I'm looking for more detail on rolling my own catching block inside a using block.

编辑:我想避免的是不必使用一个try / catch /终于我用块内像@Blair显示。但也许这是一个非问题...

What I wanted to avoid is having to use a try/catch/finally inside my using block like @Blair showed. But maybe this is a non issue...

编辑:@Blair,这正是我一直在寻找,感谢您的详细答复

@Blair, this is exactly what I was looking for, thanks for the detailed reply!

推荐答案

我真的不明白的问题 - 你抛出一个异常,你通常会。 如果 MyThing 工具的IDisposable ,那么:

I don't really understand the question - you throw an exception as you normally would. If MyThing implements IDisposable, then:

using ( MyThing thing = new MyThing() )
{
    ...
    throw new ApplicationException("oops");
}

thing.Dispose 你离开该块将被调用,因为异常的抛出。如果你想一个try / catch /终于结合和使用,您可以嵌套它们:

And thing.Dispose will be called as you leave the block, as the exception's thrown. If you want to combine a try/catch/finally and a using, you can either nest them:

try
{
    ...
    using ( MyThing thing = new MyThing() )
    {
        ...
    }
    ...
}
catch ( Exception e )
{
    ....
}
finally
{
    ....
}

(或者放的try / catch /终于在使用):

(Or put the try/catch/finally in the using):

using ( MyThing thing = new MyThing() )
{
    ...
    try
    {
        ...
    }
    catch ( Exception e )
    {
        ....
    }
    finally
    {
        ....
    }    
    ...
} // thing.Dispose is called now

或者你也可以展开的使用和显式调用处置最后块@ 吵闹证实,并称需要在终于任何额外的异常处理或-recovery code (或)。

Or you can unroll the using and explicitly call Dispose in the finally block as @Quarrelsome demonstrated, adding any extra exception-handling or -recovery code that you need in the finally (or in the catch).

编辑:在回答@ Toran比卢普斯,如果​​你需要从确保预留处理异常,你的处置方法被调用时,你要么必须使用使用的try / catch /终于或展开的使用 - 我不认为有来完成你想要的任何其他方式

In response to @Toran Billups, if you need to process exceptions aside from ensuring that your Dispose method is called, you'll either have to use a using and try/catch/finally or unroll the using - I don't thinks there's any other way to accomplish what you want.

这篇关于如何捕捉使用块与.NET 2.0中的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆