1、finally語句不會被執行的狀況,至少有以下兩種java
2、return語句的關係bash
public class FinallyReturnTest { public static void main(String[] args) { System.out.println(test()); } public static String test() { try { System.out.println("try block"); return getResult(); } finally { System.out.println("finally block"); } } public static String getResult() { System.out.println("get result"); return "result"; }}複製代碼
返回結果app
try block
get result
finally block
result
Process finished with exit code 0複製代碼
2.try中的返回值可能由於finally裏的修改也可能不變ui
test1:spa
複製代碼
public class FinallyReturnTest1 { public static void main(String[] args) { System.out.println(test()); } public static int test() { int b = 20; try { System.out.println("try block"); return b += 80; } catch (Exception e) { System.out.println("catch block"); } finally { System.out.println("finally block"); if (b > 25) { System.out.println("b>25, b = " + b); } b = 150; } return 2000; }}複製代碼
返回結果
code
try block
finally block
b>25, b = 100
100複製代碼
test2:ip
複製代碼
public class FinallyReturnTest2 { public static void main(String[] args) { System.out.println(getMap().get("KEY")); } public static Map<String, String> getMap() { Map<String, String> map = new HashMap<>(); map.put("KEY", "INIT"); try { map.put("KEY", "TRY"); return map; } catch (Exception e) { map.put("KEY", "CATCH"); } finally { map.put("KEY", "FINALLY"); map = null; } return map; }}
複製代碼
返回結果
get
FINALLY
Process finished with exit code 0複製代碼
三、try塊裏的return語句在異常的狀況下不會被執行,這樣具體返回哪一個看狀況虛擬機
①catch和finally塊裏無返回語句,返回finally外的return語句。string
②若是catch塊裏無返回語句,finally裏有返回語句,返回finally的return語句。
③若是catch塊裏有return語句,執行的狀況和try同樣,finally有返回語句,執行finally中的返回語句。
3、字節碼角度理解
public int get();
descriptor: ()I
flags: ACC_PUBLIC
Code:
stack=1, locals=4, args_size=1
0: iconst_0 將int型0推送至棧頂(操做數棧) 1: istore_1 將棧頂int型數值存入第二個本地變量(局部變量表) 2: iconst_2 將int型2推送至棧頂 3: ireturn 從當前方法返回int,返回finally中的return值 2 4: astore_1 將棧頂引用型數值存入第二個變量(出現異常,將Exception存入局部變量表) 5: aload_1 將第二個引用型本地變量推送至棧頂 6: invokevirtual #3// Method java/lang/Exception.printStackTrace:()V 調用Exception實例方法 9: iconst_1 將int型1推送至棧頂 10: istore_2 將棧頂int型數值存入第三個本地變量 11: iconst_2 將int型2推送至棧頂 12: ireturn 從當前方法返回int,返回finally中的return值 13: astore_3 將棧頂引用型數值存入第四個變量 14: iconst_2 將int型2推送至棧頂 15: ireturn 從當前方法返回int,返回finally中的return值 2 Exception table: from to target type 0 2 4 Class java/lang/Exception 0 2 13 any 4 11 13 any LineNumberTable: line 7: 0 line 12: 2 line 8: 4 line 9: 5 line 10: 9 line 12: 11
複製代碼