異常處理是編寫健壯程序的基礎。本文通過一個「輸入兩數相加」的案例,演示 Scanner.nextInt() 遇到非數字輸入拋出 InputMismatchException 的捕獲與處理流程,並說明異常對象常用方法與最佳實踐。
import java.util.InputMismatchException;
import java.util.Scanner;
public class ExceptionDemo1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("請輸入數字給第一個加數賦值:");
int num1 = 0;
try {
num1 = sc.nextInt(); // 若輸入 "abc" 拋出 InputMismatchException
} catch (InputMismatchException e) {
System.out.println("輸入的信息中出現數字以外的其他字符。");
sc.nextLine(); // 關鍵:清空緩衝區殘留的非法輸入,防止死循環
}
int num2 = 123;
System.out.println(num1 + "+" + num2 + "=" + (num1 + num2));
}
}
| 輸入 | 控制台輸出 | 說明 |
|---|---|---|
88 | 88+123=211 | 正常數字,try 塊完成,catch 不執行 |
abc | 輸入的信息中出現數字以外的其他字符。 | 拋出異常,catch 捕獲,num1 保持初始值 0 |
12.5 | 輸入的信息中出現數字以外的其他字符。 | 小數非整數,同樣拋出 InputMismatchException |
sc.nextLine() 清空緩衝區?Scanner.nextInt() 讀取失敗時不消耗緩衝區中的非法字符,若不清理,後續循環調用會反覆讀取同一非法輸入導致無限循環拋出異常。
| 方法 | 返回值 | 用途 |
|---|---|---|
e.getMessage() | String | 異常詳細描述(如 "For input string: \"abc\"") |
e.toString() | String | 異常類名 + 描述(如 "java.util.InputMismatchException: For input string: \"abc\"") |
e.printStackTrace() | void | 輸出完整堆棧軌跡至標準錯誤流,調試必備 |
e.getCause() | Throwable | 獲取根因異常(鏈式異常) |
Throwable
├── Error (嚴重錯誤,不可恢復,如 OutOfMemoryError)
└── Exception (異常,可捕獲處理)
├── RuntimeException (運行時異常,非受檢,如 NullPointerException, InputMismatchException)
└── IOException 等 (受檢異常,編譯強制處理)
public static int readInt(Scanner sc, String prompt) {
while (true) {
System.out.print(prompt);
try {
return sc.nextInt();
} catch (InputMismatchException e) {
System.out.println("輸入無效,請輸入整數。");
sc.nextLine(); // 清空緩衝區
}
}
}
// 使用
int num = readInt(new Scanner(System.in), "請輸入年齡:");
InputMismatchException)而非通用 Exception,避免吞沒其他錯誤。try-with-resources(Java 7+)自動關閉 Scanner。e.printStackTrace() 而非直接輸出控制台。