阿摩線上測驗 登入

申論題資訊

試卷:101年 - 101 高等考試_三級_資訊處理:程式語言#26526
科目:程式語言
年份:101年
排序:0

題組內容

四、請回答下列關於例外處理(exception handling)的問題:

申論題內容

⑵下列 Java 程式的執行結果為何?(12 分) class FooException extends Exception {} class ExceptionQuestion { public void aMethod() throws FooException { try { System.out.println( "In aMethod" ); throw new FooException(); } catch ( FooException error ) { System.out.println( "in first catch" ); throw new FooException(); } finally { System.out.println( "Finally" ); } } public static void main( String[] args ) { try { System.out.println( "Start" ); ExceptionQuestion x = new ExceptionQuestion(); x.aMethod(); System.out.println( "After method" ); } catch ( FooException e1 ) { System.out.println( "In handler 1" ); } catch ( Exception e2 ) { System.out.println( "In handler 2" ); } System.out.println( "End" ); } }

詳解 (共 1 筆)

詳解 提供者:114年高考上榜

Start
In aMethod
in first catch
Finally
In handler 1
End

程式開始執行,首先輸出 "Start",接著呼叫 aMethod() 方法。在 aMethod() 中,程式進入 try 區塊,輸出 "In aMethod",然後拋出 FooException 例外。因為 FooException 是在 throws 子句中被宣告的,所以這個例外被拋出去。
 
接著程式進入 catch 區塊,處理 FooException 例外。在這裡輸出 "in first catch",然後又拋出了一個新的 FooException 例外。
 
接下來程式進入 finally 區塊,輸出 "Finally",然後回到 aMethod() 的呼叫處。由於 aMethod() 宣告了 throws FooException,所以這個例外被拋出去。
 
回到 main() 方法中,aMethod() 拋出的 FooException 例外被捕捉到,程式進入第一個 catch 區塊,輸出 "In handler 1"。
最後,程式輸出 "End"。
 
因為在 aMethod() 中拋出的例外類型是 FooException,而第一個 catch 區塊處理的也是 FooException,所以第二個 catch 區塊永遠不會被執行。