初學者常見困惑:dividend = Integer.parseInt(args[0]) 中的 args[0] 究竟從哪裡來?以下完整代碼演示了異常處理與參數解析:
package yichang;
public class MyExceptionTest {
public static void main(String[] args) {
int dividend = 0;
int divisor;
int result = 0;
try {
dividend = Integer.parseInt(args[0]);
divisor = Integer.parseInt(args[1]);
result = dividend / divisor;
System.out.println("result=" + result);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("輸入參數量太少,請輸入兩個參數");
} catch (NumberFormatException e) {
System.out.println("參數格式不對,請輸入兩個數字");
} catch (ArithmeticException e) {
System.out.println("除數為0");
}
}
}
100 20(空格分隔)

args 是 String[] 類型,索引從 0 開始Integer.parseInt() 將字符串轉為整數,非數字拋出 NumberFormatExceptionArrayIndexOutOfBoundsExceptionArithmeticException配置完成後,控制台將正確輸出:result=5(以 100/20 為例)。