捕获在使用块的目标对象的构造函数抛出的异常 [英] Catching exceptions thrown in the constructor of the target object of a Using block

查看:132
本文介绍了捕获在使用块的目标对象的构造函数抛出的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

using(SomeClass x = new SomeClass("c:/temp/test.txt"))
{
...
}

using块内部,所有的罚款与治疗例外正常。但是,如果 SomeClass的的构造函数可以抛出什么异常?

Inside the using block, all is fine with treating exceptions as normal. But what if the constructor of SomeClass can throw an exception?

推荐答案

,当构造函数抛出异常,这将是一个问题。 所有你能做的就是换一个try / catch块中使用的块。这也是为什么必须这样做的。

Yes, this will be a problem when the constructor throws an exception. All you can do is wrap the using block within a try/catch block. Here's why you must do it that way.

使用块只是语法糖和编译器替换每个使用块具有同等的try / finall块。唯一的问题是,编译器不会在try块内包装的构造。编译后的代码将有以下的IL转换。

using blocks are just syntactic sugar and compiler replaces each using block with equivalent try/finall block. The only issue is that the compiler does not wrap the constructor within the try block. Your code after compilation would have following conversion in the IL.

        //Declare object x of type SomeClass.
        SomeClass x;

        //Instantiate the object by calling the constructor.
        x = new SomeClass("c:/temp/test.txt");

        try
        {
            //Do some work on x.
        }
        finally
        {
            if(x != null)
                x.Dispose();
        }

你可以从代码中看到,对象x不会在实例化情况下,当构造函数抛出异常,控制将不会从异常点提高,如果不处理,继续移动。

As you can see from the code, the object x will not be instantiated in case when the constructor throws an exception and the control will not move further from the point of exception raise if not handled.

我刚才已经发布了的博客,帖子就这个问题我的博客昨晚。

I have just posted a blog-post on my blog on this subject last night.

我刚才想知道为什么C#
设计者没有try块
而根据我应该已经
进行内包装对象
建设。

I'm just now wondering why C# designers did not wrap object construction within the try block which according to me should have been done.

我想我找到了答案,为什么C#不换行对象建设纳入到位using块生成try块。

原因很简单。如果你包裹在try块中同时声明和实例然后的对象将是超出范围的程序finally块和代码不会在因为编译,为最终阻断对象几乎不存在。如果你只包裹建设中的try块和try块之前保持的声明,即使在这种情况下,它不会因为编译它找到你要使用指定的变量

The reason is simple. If you wrap both declaration and instantiation within the try block then the object would be out of scope for the proceeding finally block and the code will not compile at because, for finally block the object hardly exists. If you only wrap the construction in the try block and keep declaration before the try block, even in that case the it will not compile since it finds you're trying to use an assigned variable.

这篇关于捕获在使用块的目标对象的构造函数抛出的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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