finally中的return


  周五晚6點下班去面試,出了一份筆試題,看到第一題有些蒙了,雖然以前遇到過類似的問題,但並沒有留心記一下,覺得沒人會這樣寫代碼,但實際上沒有面試題中是有的。

1,有在try塊中執行不到finally的情況嗎?

  肯定是有,在try塊中有System.exit(0);這樣的語句,System.exit(0);是終止Java虛擬機JVM的,連JVM都停止了,所有都結束了,當然finally語句也不會被執行到。

2,try和finally中的try,哪一個會被執行?

  肯定是finally中的,因為無論try中寫了多少return,在return的一剎那,會被finally捕獲,之后執行finally中的代碼,finally中return了就沒有try中return什么事了。

3,try中return后的代碼會執行嗎?

  會的,調用finally的時機是try塊真的要return時。

 1 public class FinallyTest3 {  2 
 3     public static void main(String[] args) {  4 
 5  System.out.println(test3());  6  }  7 
 8     public static int test3() {  9         int b = 20; 10 
11         try { 12             System.out.println("try block"); 13 
14             return b += 80; 15         } catch (Exception e) { 16 
17             System.out.println("catch block"); 18         } finally { 19 
20             System.out.println("finally block"); 21 
22             if (b > 25) { 23                 System.out.println("b>25, b = " + b); 24  } 25 
26             b = 150; 27  } 28 
29         return 2000; 30  } 31 
32 }

結果為

try block
finally block
b>25, b = 100
100
 1 import java.util.*;  2 
 3 public class FinallyTest6  4 {  5     public static void main(String[] args) {  6         System.out.println(getMap().get("KEY").toString());  7  }  8      
 9     public static Map<String, String> getMap() { 10         Map<String, String> map = new HashMap<String, String>(); 11         map.put("KEY", "INIT"); 12          
13         try { 14             map.put("KEY", "TRY"); 15             return map; 16  } 17         catch (Exception e) { 18             map.put("KEY", "CATCH"); 19  } 20         finally { 21             map.put("KEY", "FINALLY"); 22             map = null; 23  } 24          
25         return map; 26  } 27 }

結果為

FINALLY
為什么測試用例1中finally里的b = 150;並沒有起到作用而測試用例2中finally的map.put("KEY", "FINALLY");起了作用而map = null;卻沒起作用呢?這就是Java到底是傳值還是傳址的問題了,簡單來說就是:Java中只有傳值沒有傳址,這也是為什么map = null這句不起作用。這同時也說明了返回語句是try中的return語句而不是 finally外面的return b;這句,不相信的話可以試下,將return b;改為return 294,對原來的結果沒有一點影響。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM