定義異常類
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 捕獲,實現業務語義化的錯誤傳遞。