【问题标题】:Explain "finally"'s use in try-catch-finally blocks解释“finally”在 try-catch-finally 块中的用法
【发布时间】:2013-12-16 08:15:39
【问题描述】:

我读到finally 键使try-catch 块最终工作,甚至函数是否抛出异常。但我想知道如果我不将代码放入 finally 块(如下面的 Function_2)中会有什么不同,这是我用来编码的方式。谢谢!

void Function_1()
{
    try
    {
        throw new Exception();
    }
    catch
    {
    }
    finally                                   //Have finally block
    {
        Other_Function();
    }
}

void Function_2()
{
    try
    {
        throw new Exception();
    }
    catch
    {
    }

    Other_Function();                        //Don't have finally block
}

【问题讨论】:

  • throw new Exception() 替换为return,您会看到不同之处。

标签: c# .net try-catch-finally


【解决方案1】:

finally 块是指始终执行的语句块,无论应用程序执行期间可能发生的意外事件或异常如何。 finally 块的执行旨在释放资源,例如数据库连接,这些资源通常是有限的。

来自MSDN

通常,当未处理的异常结束应用程序时,无论是 不是 finally 块运行并不重要。但是,如果你有 即使在这种情况下也必须运行的 finally 块中的语句, 一种解决方案是在 try-finally 语句中添加一个 catch 块。 或者,您可以捕获可能在 调用堆栈更高的 try-finally 语句的 try 块。那 就是,可以在调用方法的方法中捕获异常 包含 try-finally 语句,或在调用的方法中 该方法,或调用堆栈中的任何方法。如果异常是 没有被捕获,finally 块的执行取决于 操作系统选择触发异常展开操作。

【讨论】:

  • 您可能想将您写的第一句话与您引用的最后一句话进行比较。特别是“总是”和“依赖”这两个词
【解决方案2】:

finally 块中的代码总是被执行。最后提供了一个确保程序正确执行的结构。它确保在退出封闭方法之前始终到达语句块。 他的程序展示了 finally 子句如何成为程序控制流的一部分。在这个程序中,会生成一个随机数。该值用于确定是抛出异常、立即返回还是什么都不做。

using System;

class Program
{
    static void Main()
    {
    try
    {
        // Acquire random integer for use in control flow.
        // ... If the number is 0, an error occurs.
        // ... If 1, the method returns.
        // ... Otherwise, fall through to end.
        int random = new Random().Next(0, 3); // 0, 1, 2
        if (random == 0)
        {
        throw new Exception("Random = 0");
        }
        if (random == 1)
        {
        Console.WriteLine("Random = 1");
        return;
        }
        Console.WriteLine("Random = 2");
    }
    finally
    {
        // This statement is executed before the Main method is exited.
        // ... It is reached when an exception is thrown.
        // ... It is reached after the return.
        // ... It is reached in other cases.
        Console.WriteLine("Control flow reaches finally");
    }
    }
}

Source

【解决方案3】:

如果我没有将代码放在 finally 块中(如下面的 Function_2)

如果您不将代码放入 finally 中,除非您不会收到异常,否则代码块将被执行。

但是,如果您在该代码块(最终未保留在内部)之前遇到异常,则控件将自行从那里返回。

但如果您将代码保存在 finally 中,无论情况如何,它都会执行。

示例:1 没有 finally 块

 try
    {
    //throw exption
    }
    catch
    {
    //return from here
    }

    //below statement won't get executed
    Other_Function(); 

示例:2 带有 finally 块

  try
    {
    //throw exption
    }
    catch
    {
    //return from here if finally block is not available 
    //if available execute finally block and return
    }
    finally
    {
    //below statement surly gets executed
    Other_Function(); 
    }

【讨论】:

    猜你喜欢
    • 2015-09-05
    • 1970-01-01
    • 2011-08-31
    • 2011-06-01
    • 2014-11-27
    • 1970-01-01
    • 2012-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多