阿摩線上測驗 登入

申論題資訊

試卷:96年 - 096年專門職業及技術人員高等建築師、技師、法醫師暨普通記帳士、96年第二次高等暨普通消防設備人員、普通不動產經紀人資訊技師#32449
科目:程式設計
年份:96年
排序:0

題組內容

二、請問下列指令在 MS-DOS 執行的結果為何?

申論題內容

⑵ > java TT 11 2 (10 分) public class TT { public static void theX() throws Exception{ System.out.println(“TheX”); throw new Exception(“Throw an exception”);} public static void main(String[] args) { try { int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); System.out.println(“at Try”); int c = a / b; if (c > 1) { theX(); } } catch (Exception e) { System.out.println(“at Exception” + e.toString());} finally { System.out.println(“finally”); } } }

詳解 (共 3 筆)

詳解 提供者:thisismichae98
at Try TheX at Exceptionjava.lang.Exception: Throw an exception finally
詳解 提供者:永不放棄
at Exception 0 finally
詳解 提供者:hchungw
當你運行Java代碼java TT 11 2時,該程式會接受兩個命令行參數11和2,然後執行main方法中的邏輯。
下面是代碼的逐步執行過程和輸出分析:
解析命令行參數:將args[0](即"11")和args[1](即"2")解析為整數a=11和b=2。
執行Try區塊:首先輸出"at Try"。
計算並判斷:計算c = a / b,即c = 11 / 2得到c = 5,因為c > 1,條件成立,所以呼叫theX方法。
執行theX方法:theX方法被執行,首先輸出"TheX",然後拋出一個異常Exception("Throw an exception")。
捕獲異常:try區塊中拋出的異常被catch塊捕獲,因此輸出"at Exception"和異常的toString方法的返回值,即java.lang.Exception: Throw an exception。
執行Finally區塊:無論是否捕獲到異常,finally區塊始終被執行,因此輸出"finally"。
綜上所述,該Java程式的輸出將會是:
vbnet
Copy code
at Try
TheX
at Exceptionjava.lang.Exception: Throw an exception
finally
請注意,輸出中"at Exception"和異常信息之間沒有空格,這是因為程式中的+運算符直接將字符串"at Exception"和e.toString()的結果拼接在了一起。如果需要在它們之間添加空格,可以將相應的代碼行修改為:
java
Copy code
System.out.println(“at Exception ” + e.toString());