为什么打印1?

Ser*_*zov -1 java try-finally

我有代码:

class Test {
  public static void main(final String [] args) {
    System.out.println(foo());
  }

  private static int foo() {
    int a = 0;
      try {
        ++a;
        return a;
      } finally {
        a = 10;
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)

我无法理解为什么打印1.

Sud*_*hul 6

try {
    ++a;
    return a; // 1 is returned here
} finally {
    a = 10; // a is assigned with 10 later.
}
Run Code Online (Sandbox Code Playgroud)

a增加并在try块本身中返回.发布此信息后return,将afinally块中重新分配值.这就是为什么它打印1的原因.


引用文档.这应该可以帮助您更清楚地理解它.

最后编译

try-finally语句的编译类似于try-catch.在try语句之外传递控制之前,无论该传输是正常还是突然,因为抛出了异常,必须首先执行finally子句.对于这个简单的例子:

void tryFinally() {
    try {
        tryItOut();
    } finally {
        wrapItUp();
    }
}
Run Code Online (Sandbox Code Playgroud)

编译后的代码是:

Method void tryFinally()
0   aload_0             // Beginning of try block
1   invokevirtual #6    // Method Example.tryItOut()V
4   jsr 14              // Call finally block
7   return              // End of try block
8   astore_1            // Beginning of handler for any throw
9   jsr 14              // Call finally block
12  aload_1             // Push thrown value
13  athrow              // ...and rethrow value to the invoker
14  astore_2            // Beginning of finally block
15  aload_0             // Push this
16  invokevirtual #5    // Method Example.wrapItUp()V
19  ret 2               // Return from finally block
Exception table:
From    To      Target      Type
0       4       8           any
Run Code Online (Sandbox Code Playgroud)

控制传递到try语句之外有四种方法:

  1. 通过掉落在那个街区的底部
  2. 回来
  3. 通过执行break或continue语句
  4. 通过提出例外.