首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java try-catch-finally 異常處理中循環繼續輸入的正確模式

     編輯:程式設計綜合問答

錯誤模式


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。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved