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

标签 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);
        }
    }
}

或者...

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);
            }
        }

    }
}

最佳答案

两者都可以,具体取决于您要在捕获中做什么。如果您需要在 catch 中使用 f,那么它需要在 using 语句中。但是在您的示例中没有区别。

编辑: 正如在其他地方指出的那样,它还取决于您是试图仅捕获在 using 之后的 block 中生成的异常,还是在 using 语句中包含对象创建。如果它在 using 之后的 block 中,那么它就像我描述的那样。如果你想捕获 Foo f = new Foo() 产生的异常,那么你需要使用第一种方法。

关于c# - 在代码中使用 '"using"关键字时,我应该在哪里捕获异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3395518/

相关文章:

node.js - 如何在 node.js 中捕获 zlib 错误

r - tryCatch 抑制错误消息

c# - 如何创建继承自TextBox的类

javascript - 如何从 CMD 命令行启动 Node.js 应用程序,并从另一个 .Net core 3.0 应用程序调用它?

c# - 反序列化响应

javascript - "in"运算符或 obj.hasOwnProperty(prop) 的 Big O 表示法的效率是多少

php - 拥有基于特定设计的庞大数据库(用于性能测试)

c# - 在 VS Express 2010 中混合 C++ 和 C# 项目

c++ - 是否每个循环都会评估基于 C++11 范围的 for 循环条件?

c# - 包含对多列的查询