錯誤模式
try {
while (true) { /* 輸入計算 */ }
} catch (Exception e) { /* 處理 */ }
// 捕獲異常後跳出循環,無法繼續輸入
正確模式:標誌位控制循環
Scanner s = new Scanner(System.in);
boolean retry = true;
while (retry) {
retry = false;
try {
int a = s.nextInt();
int b = s.nextInt();
System.out.println("余數: " + (a % b));
} catch (Exception e) {
System.out.println("輸入錯誤,請重新輸入");
s.nextLine(); // 清空緩衝區殘留換行/非數字
retry = true; // 設置標誌,外層 while 繼續
}
}
關鍵點
- 將
try-catch 放在 **循環體內部**,捕獲異常後不跳出循環。
- 用
boolean retry 控制是否重試。
s.nextLine() 清理緩衝區,防止無限循環讀取同一錯誤輸入。
- 生產代碼建議捕獲具體異常(
InputMismatchException, ArithmeticException)而非笼統 Exception。