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)
另外,如果去掉上例中被註釋的兩條語句前的註釋符,執行結果則是:
1
|
return
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