简体   繁体   English

使用初始化内部的异常

[英]Exception inside using initialization

I read many threads about the using keyword in C#, but I couldn't find anyone with the same question. 我在C#中阅读了许多有关using关键字的主题,但找不到任何人遇到相同的问题。 Reading this interesting article, it says that the using statement is basically equivalent to a try/catch block: 阅读这篇有趣的文章时,它说using语句基本上等效于try / catch块:

MyResource myRes= new MyResource();
try
{
    myRes.DoSomething();
}
finally
{
    // Check for a null resource.
    if (myRes!= null)
        // Call the object's Dispose method.
        ((IDisposable)myRes).Dispose();
}

What really makes me going mad is that the object initialization myRes= new MyResource() is still outside of the try/catch block, so if something goes wrong during the initialization (oh, and it does!) I have no other way to handle it than using a normal try/catch block. 真正让我发狂的是,对象初始化myRes= new MyResource()仍在try / catch块之外,因此,如果在初始化过程中出现问题(哦,确实如此!),我没有其他方法可以处理而不是使用普通的try / catch块。

Is this correct or am I missing something? 这是正确的还是我错过了什么? In my opinion, this makes the sense of the using statement partially useless. 在我看来,这使得意义上的using语句部分无用。

I also tried something like this: 我也尝试过这样的事情:

using (MyResource myRes)
{
    myRes = new MyResource();
    myRes.DoSomething();
}

but the compiler don't like this, so it is not possible to bring the initialization inside of the try block. 但是编译器不喜欢这样,因此不可能将初始化带入try块内部。

This seems so strange to me that I think that I must be missing something. 这对我来说似乎很奇怪,以至于我一定想念一些东西。 Could anyone explain me the reasons behind this? 谁能解释我背后的原因?

Well if the constructor fails, the exception will be thrown instead of the reference being returned - so the calling code has nothing to dispose. 好吧,如果构造函数失败,则将抛出异常, 而不是返回引用 -因此,调用代码无须处理。

Basically, constructors need to be careful. 基本上,构造函数需要小心。 If an exception is thrown in an exception, the constructor needs to make sure no resources are leaked, because nothing else is going to get a chance to clean up. 如果在异常中引发了异常,则构造函数需要确保没有资源泄漏,因为其他任何东西都没有机会进行清理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM