1、finally是否執行:ide
1.只有與 finally 相對應的 try 語句塊獲得執行的狀況下,finally 語句塊纔會執行
當finally 相對應的 try 語句塊以前,已經拋出錯誤,或者已經返回,return,就不會執行finallyspa
2.當與 finally 相對應的 try 語句塊中有 System.exit(int status) ,而且順利執行,finally 語句塊也不會執行
System.exit(int status) 會終止 Java 虛擬機的運行
相似的狀況還有:線程被中斷,interrupted,進程被終止,killed,死機、斷電等線程
2、finally什麼時候執行:code
1.Java 虛擬機會把 finally 語句塊做爲 subroutine 直接插入到 try 語句塊或者 catch 語句塊的控制轉移語句以前。
控制轉移語句:return、throw 和 break、continueblog
2.對於有返回值的 return 和 throw 語句,在執行 subroutine 以前,try 或者 catch 語句塊會保留其返回值到本地變量表(Local Variable Table)中。
待 subroutine 執行完畢以後,再恢復保留的返回值到操做數棧中,而後經過 return 或者 throw 語句將其返回給該方法的調用者(invoker)。進程
1 public class Test { 2 3 public static void main(String[] args) { 4 System.out.println(testFinally()); 5 } 6 7 public static int testFinally() { 8 int i = 1; 9 // if(i == 1) 10 // return 0; 11 System.out.println("before try"); 12 i = i / 0; 13 try { 14 System.out.println("try"); 15 //System.exit(0); 16 return i; 17 } finally { 18 System.out.println("finally"); 19 } 20 } 21 }
1 public class Test { 2 3 public static void main(String[] args) { 4 System.out.print(testFinally()); 5 } 6 7 public static int testFinally() { 8 int b = 10; 9 try { 10 System.out.println("try"); 11 return b += 20; 12 } catch (Exception e) { 13 System.out.println("error:" + e); 14 } finally { 15 System.out.println("finally"); 16 System.out.println("b:" + b); 17 b = 50; 18 System.out.println("b:" + b); 19 } 20 return 40; 21 } 22 }