在代码中使用'"using"关键字时,我应该在哪里捕获异常?

xpo*_*ort 11 c# performance exception-handling

哪一个结构更好?

class Program
{
    static void Main(string[] args)
    {
        try
        {
            using (Foo f = new Foo())
            {
                //some commands that potentially produce exceptions.
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

要么...

class Program
{
    static void Main(string[] args)
    {

        using (Foo f = new Foo())
        {
            try
            {
                //some commands that potentially produce exceptions.
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

btl*_*log 7

要么是好的,取决于你将要捕获的内容.如果你需要f在catch中使用它,那么它需要在using语句中.但是在你的例子中没有区别.

编辑:正如其他地方所指出的那样,它还取决于您是否尝试捕获在使用或在using语句中包含对象创建后在块中生成的异常.如果它在使用之后的块中那么它就像我描述的那样.如果要捕获Foo f = new Foo()当时生成的异常,则需要使用第一种方法.


Pra*_*ana 1

查看这篇文章以更好地理解:http://www.ruchitsurati.net/index.php/2010/07/28/understanding-%E2%80%98using%E2%80%99-block-in-c/

另请阅读此问题的答案:Catching exceptions throws in the constructor of the target object of a using block

第一个更好

class Program
{
    static void Main(string[] args)
    {
        try
        {
            using (Foo f = new Foo())
            {
                //some commands that potentially produce exceptions.
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

因为如果您看到此 try 和 catch 块的 IL 代码,则不会包装对象的初始化。