number1:
很多人都认为 finally 语句块是肯定要执行的,其中也包括一些很有经验的 Java 程序员。可惜并不像大多人所认为的那样,对于这个问题,答案当然是否定的,我们先来看下面这个例子。
public class Test {
public static void main(String[] args) {
System.out.println("return value of test(): " + test());
}
public static int test() {
int i = 1;
// if(i == 1)
// return 0;
System.out.println("the previous statement of try block");
i = i / 0;
try {
System.out.println("try block");
return i;
}finally {
System.out.println("finally block");
}
}
}
number1执行结果:
the previous statement of try block
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Foo.Test.test(Test.java:14)
at Foo.Test.main(Test.java:5)另外,如果去掉上例中被注释的两条语句前的注释符,执行结果则是:
1return
value of test():
0
在以上两种情况下,finally 语句块都没有执行,说明什么问题呢?只有与 finally 相对应的 try 语句块得到执行的情况下,finally 语句块才会执行。以上两种情况,都是在 try 语句块之前返回(return)或者抛出异常,所以 try 对应的 finally 语句块没有执行。
number2:
public class Test {
public static void main(String[] args) {
foo(false);
}
public static void foo(boolean flag) {
System.out.println("enter foo()");
if(flag) {
try {
System.out.println("enter try block");
} finally {
System.out.println("enter finally block");
}
} else {
System.out.println("leave foo()");
}
}
}
/****************** 控制台打印如下 enter foo() leave foo() *******************/
number3:
public class Foo {
public static void main(String[] args) {
try {
return;
} finally {
System.out.println( "Finally" );
}
}
}执行结果就是Finally