如何处理异常的处置抛出? [英] How to handle exception thrown from Dispose?

查看:158
本文介绍了如何处理异常的处置抛出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我正在研究有关对象未设置。一些棘手的bug

Recently, I was researching some tricky bugs about object not disposed.

我发现在code一些模式。据报道,一些m_foo不设置,而似乎SomeClass的的所有实例已被释放。

I found some pattern in code. It is reported that some m_foo is not disposed, while it seems all instances of SomeClass has been disposed.

public class SomeClass: IDisposable
{
    void Dispose()
    {
       if (m_foo != null)
       {
          m_foo.Dispose();
       }
       if (m_bar != null)
       {
          m_bar.Dispose();
       }   
    }

    private Foo m_foo;

    private Bar m_bar;

}

我怀疑Foo.Dispose可能抛出一个异常,所以不执行以下code所以m_bar未设置。

I suspects that Foo.Dispose might throw a exception, so that following code is not executed so m_bar is not disposed.

由于富/酒吧可能是来自第三方的,所以它不能保证不抛出异常。

Since Foo/Bar might be from third party, so it is not guaranteed to not throwing exception.

如果只是包装的所有处置与调用的try-catch中,code会变成笨拙。

If just wrap all Dispose invocation with try-catch, the code will turn to be clumsy.

什么是最好的做法来处理呢?

What's best practice to handle this?

推荐答案

其真正的,它可以是pretty的不好的泄漏异常的处置方法,特别是东西,实现IDisposable通常会指定一个终结了会调用Dispose。

Its true that it can be pretty bad to leak out an exception of your dispose method, especially since stuff that implements IDisposable will usually specify a finalizer that will call Dispose.

现在的问题是,通过处理异常席卷下的地毯的问题,可能会留给你一些非常难以调试的情况下。如果你的IDisposable接口分配的,只有处置后得到释放各种各样的关键部分。如果你忽视的事实是异常发生,你可能会在僵局的中心。我认为,在处置的失败应该是要早期失败的情形之一的,这样你就可以尽快的发现修复bug。

The problem is that sweeping the problem under of the carpet by handling an exception may leave you with some very hard-to-debug situations. What if your IDisposable allocated a critical section of sorts that only gets released after dispose. If you ignore the fact that the exception happened, you may end up in deadlock central. I think failures in Dispose should be one of those cases where you want to fail early, so you can fix the bug as soon as its discovered.

当然,这一切都取决于该对象被设置,对于一些对象,你可能能够恢复,其他人没有。根据经验,一般情况下只要正确使用,处置不应该​​抛出异常,你不应该有code防守各地要调用嵌套的Dispose方法例外。

Of course it all depends on the object being disposed, for some objects you may be able to recover, others not. As a general rule of thumb, Dispose should not throw exceptions when used correctly and you should not have to code defensively around exceptions in nested Dispose methods you are calling.

难道你真的不想扫在地毯下一个OutOfMemoryException?

Do you really do not want to sweep an OutOfMemoryException under the carpet?

如果我有一个狡猾的第三方组件随意扔在例外情况处置我会得到固定和主机它,我可以推倒的时候就开始玩了一个单独的进程。

If I had a dodgy 3rd party component that arbitrarily threw exceptions on Dispose I would get it fixed AND host it in a separate process that I could tear down when it started playing up.

这篇关于如何处理异常的处置抛出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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