我對基本的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!");
}
}
謝謝StrixVaria a nd Veger昨天快速回答! – user2127664 2013-03-06 17:42:59