2016-04-11 140 views
-1
public class Main { 

    public static void main(String[] args) { 
     System.out.println("Normal: " + testNormal()); 
     System.out.println("Exception: " + testException()); 
    } 

    public static int testNormal() { 
     try { 
      // no exception 
      return 0; 
     } catch (Exception e) { 
      System.out.println("[normal] Exception caught"); 
     } finally { 
      System.out.println("[normal] Finally"); 
     } 
     System.out.println("[normal] Rest of code"); 
     return -1; 
    } 

    public static int testException() { 
     try { 
      throw new Exception(); 
     } catch (Exception e) { 
      System.out.println("[except] Exception caught"); 
     } finally { 
      System.out.println("[except] Finally"); 
     } 
     System.out.println("[except] Rest of code"); 
     return -1; 
    } 

} 

爲什麼「[normal]其餘代碼」不能執行和「[except]其餘代碼」不能執行?請解釋。解釋代碼執行的差異

+1

作業的哪部分你不明白? –

+1

你覺得'返回0;'是做什麼的? – Savior

+0

''[except]其餘代碼正在執行。 – Savior

回答

2
  1. testNormalreturn 00存儲在某個位置,finally塊中的代碼運行,然後返回該存儲的值。

  2. testException。拋出異常。運行catch中的代碼。然後運行finally塊中的代碼。然後程序控制從System.out.println繼續,並返回-1

更有趣的是finally本身包含return的情況。在這種情況下,將返回finally塊中的返回值,並丟棄之前return遇到的任何存儲值。