2013-03-05 41 views
2

我對基本的Java練習測試問題做了迴應,下面這個問題的正確答案在參加測試時滑過了我。未處理的Java異常執行方法的其餘部分?

問題:「如果沒有捕獲到異常,finally塊將會運行,並且方法的其餘部分被跳過 - TRUE或FALSE?」

我試圖證明ThrowTest類(粘貼在底部)的答案,但我發現Java異常處理有些陌生。我按照catch塊的ArrayIndexOutOfBoundsException部分註釋掉的那樣編譯類。然後我執行該類而不傳遞輸入參數,從而創建一個異常(ArrayIndexOutOfBoundsException異常)。我期望最終的System.out.println不會執行,事實上它不會。

我發現如果我取消註釋ArrayIndexOutOfBoundsException catch塊並重新編譯,該類會在運行時捕獲該特定錯誤,並在底部執行「其餘方法」println。那麼,我的代碼是否證明了「方法的其餘部分被跳過」的其餘部分,還是必須從主方法以外的方法來測試它?也許有一種更直接的測試方法。

public class ThrowTest 
{ 

    public static void main(String[] args) 
    { 
    try 
     { 
      String anyString = args[0]; 
      System.out.println("Try code executes"); 
     } 

    catch(SecurityException e) //any old exception 
     { 
      System.err.println ("Error: SecurityException. "); 
      e.printStackTrace(); 
     } 

    /* begin comment 
    catch(ArrayIndexOutOfBoundsException e) 
     { 
      System.err.println("Error: Caught ArrayIndexOutOfBoundsException. "); 
      e.printStackTrace();  
     } 
    end comment */ 

    finally 
     { 
      System.out.println("finally block executes!"); 
     } 

     System.out.println("Rest of method executes!"); 
    } 

} 

回答

0

您的代碼確實證明了一切正如您所描述的那樣。當你捕捉到一個異常時,這個方法的其餘部分就會執行。如果讓方法拋出異常,它的執行立即停止。無論哪種方式,finally塊將始終執行。

+0

謝謝StrixVaria a nd Veger昨天快速回答! – user2127664 2013-03-06 17:42:59

1

無論是拋出finally塊將始終執行(不包含任何奇怪的情況像內存不足)什麼異常,因此給出以下

try { 
    // do some code 
} 
catch (SomeException e) { 
    // exception handling 
} 
finally { 
    doFinallyStuff(); 
} 

doOtherStuff(); 

doFinallyStuff會一直執行在這裏。但doOtherStuff只會在下列條件下執行:

  • 沒有異常拋出
  • SomeException被關上,如果另一個例外是在拋出的catch塊不重新拋出異常鏈向上

try塊不是由catch塊處理,doFinallyStuff仍會執行,但doOtherStuff不會