java異常處理的面試題


 1 package test;
 2 
 3 public class Test {
 4 
 5     public static int method(int i) throws Exception {
 6         try {
 7             return 100 / i;  8         } catch (Exception ex) {
 9             throw new Exception("exception in a Method");
10         } finally {
11             System.out.printf("finally ");
12         }
13     }
14 
15     public static void main(String[] args) {
16         try {
17             method(0);
18         } catch (Exception ex) {
19             System.out.printf("exception in main ");
20         }
21         System.out.printf("finished");
22     }
23 }

運行結果:

根據結果分析的話

1)第7行生成異常對象並不會被所在的try catch捕獲,而是返回給了它的上級調用者,被調用者的try catch捕獲。

2)finally(),是無論如何都會被執行的即便try中有return也會執行只有一種方法讓finally塊不執行:System.exit()

 

關於fianlly()更多神奇的現象:http://www.cnblogs.com/lulipro/p/7504267.html#finally_return


免責聲明!

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



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