finally 块没有意义吗?

Tom*_*mmy 2 .net c# try-catch-finally

我正在自学 C#,我要学习 try、catch 和 finally。我正在使用的这本书讨论了 finally 块如何运行,而不管 try 块是否成功。但是,即使不在 finally 中,写在 catch 块之外的代码也不会运行吗?如果是这样,最后的意义是什么?这是本书提供的示例程序:

class myAppClass
{
    public static void Main()
    {
        int[] myArray = new int[5];

        try
        {
            for (int ctr = 0; ctr <10; ctr++)
            {
                myArray[ctr] = ctr;
            }
        }
        catch
        {
            Console.WriteLine("Exception caught");
        }
        finally
        {
            Console.WriteLine("Done with exception handling");
        }
        Console.WriteLine("End of Program");
        Console.ReadLine();            
    }
}
Run Code Online (Sandbox Code Playgroud)

Art*_*aca 6

这些是 afinally有用的场景:

try
{
    //Do something
}
catch (Exception e)
{
    //Try to recover from exception

    //But if you can't
    throw e;
}
finally
{
    //clean up
}
Run Code Online (Sandbox Code Playgroud)

通常您会尝试从异常中恢复或处理某些类型的异常,但是如果您无法恢复,则您没有捕获特定类型的异常,异常将被抛出给调用者,但finally无论如何都会执行该块。

另一种情况是:

try
{
    //Do something
    return result;
}
finally
{
    //clean up
}
Run Code Online (Sandbox Code Playgroud)

如果您的代码运行正常并且没有抛出异常,您可以从try块中返回并释放块中的任何资源finally

在这两种情况下,如果您将代码放在 之外try,它将永远不会被执行。