代码之家  ›  专栏  ›  技术社区  ›  Kredns

为什么要“最终”执行?

  •  17
  • Kredns  · 技术社区  · 17 年前

        int i = 0;
    Found:
        i++;
        try
        {
            throw new Exception();
        }
        catch (Exception)
        {
            goto Found;
        }
        finally
        {
            Console.Write("{0}\t", i);
        }
    

    8 回复  |  直到 16 年前
        1
  •  36
  •   Fredrik Mörk    17 年前

    以下文本来自 ( 8.9.3 The goto statement )


    goto语句执行如下:

    • 如果goto语句退出一个或多个带有关联finally块的try块,则控制权最初会转移到最内层try语句的finally块。当控件到达finally块的端点时,控件将转移到下一个封闭try语句的finally块。重复此过程,直到执行了所有中间try语句的最后一个块。
    • 控件被转移到goto语句的目标。
        2
  •  28
  •   Community Mohan Dere    9 年前

    如果有try/catch/finally或try/finally块,则执行finally块 无论您在try或catch块中有什么代码 most of the time .

    而不是GTO,考虑“返回”。

    //imagine this try/catch/finally block is inside a function with return type of bool. 
    try
    {
        throw new Exception();
    }
    catch (Exception)
    {
        return false; //Let's say you put a return here, finally block still executes.
    }
    finally
    {
        Console.WriteLine("I am in finally!");
    }
    
        3
  •  14
  •   Eric Lippert    17 年前

    finally块并不总是运行。 在许多情况下,finally块不运行。

        4
  •  3
  •   Jeremy McGee    17 年前

    finally 块始终在 try 或者 catch .

    同样地

    try
    {
      // do something
      return;
    }
    finally
    {
      // do something else
    }
    

    将始终运行 最后 块编辑-但请参见上面Eric的评论。

        5
  •  2
  •   sharptooth    17 年前

    那是故意的。在异常处理程序中,可以执行一些特定于异常的操作。在finally块中,您应该进行资源清理——这就是为什么不管异常处理代码是什么,finally块总是被执行的原因。

        6
  •  1
  •   Merus    17 年前

    如人们所说,, finally 无论程序流如何运行。当然是 块是可选的,所以如果您不需要它,就不要使用它。

        7
  •  0
  •   statenjason    17 年前

    因为 finally try (或 catch

        8
  •  0
  •   fastcodejava    16 年前

    这就是问题的关键所在 finally 块它总是(几乎)执行。