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

Java 自定義異常實戰:年齡校驗示例

     編輯:Java 綜合教學

定義異常類

public class AgeException extends Exception {
    private static final long serialVersionUID = 1L;
    public AgeException(String message) {
        super(message);
    }
}

業務邏輯與測試

public class Test {
    private int age;
    public void ageException(int age) throws AgeException {
        if (age > 0 && age <= 120) {
            this.age = age;
            System.out.println("格式正確");
        } else {
            throw new AgeException("請輸入正確年齡");
        }
    }
    public static void main(String[] args) {
        Test test = new Test();
        try {
            test.ageException(120); // 正常
            test.ageException(150); // 拋出自定義異常
        } catch (AgeException e) {
            e.printStackTrace();
        }
    }
}

關鍵點

  • 繼承 Exception 為受檢異常,強制調用者處理;繼承 RuntimeException 則為非受檢。
  • 構造器調用 super(message) 保留錯誤信息。
  • 配合 throws 聲明或 try-catch 捕獲,實現業務語義化的錯誤傳遞。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved