計算圓形和矩形面積,半徑/長寬非法時拋出異常,演示異常體系設計。
// 1. 自定義業務異常(繼承 RuntimeException 免受檢查)
class InvalidDimensionException extends RuntimeException {
public InvalidDimensionException(String message) {
super(message);
}
}
// 2. 形狀接口
interface Shape {
void getArea(); // 無參:屬性已在構造器初始化
}
// 3. 圓形實現
class Circle implements Shape {
private final int radius;
public static final double PI = 3.14;
public Circle(int radius) {
if (radius < 0) throw new InvalidDimensionException("半徑不能為負數: " + radius);
this.radius = radius;
}
@Override
public void getArea() {
System.out.println("圓面積: " + (radius * radius * PI));
}
}
// 4. 矩形實現
class Rectangle implements Shape {
private final int length, width;
public Rectangle(int length, int width) {
if (length <= 0 || width <= 0)
throw new InvalidDimensionException("長寬必須大於 0: " + length + "," + width);
this.length = length;
this.width = width;
}
@Override
public void getArea() {
System.out.println("矩形面積: " + (length * width));
}
}
// 5. 測試類
public class ExceptionDemo {
public static void main(String[] args) {
try {
Shape rect = new Rectangle(3, 4);
rect.getArea(); // 正常輸出 12
Shape circle = new Circle(-5); // 拋出異常
circle.getArea(); // 不會執行
} catch (InvalidDimensionException e) {
System.err.println("業務異常: " + e.getMessage());
} finally {
System.out.println("程序結束");
}
}
}
InvalidDimensionException 明確表達業務錯誤類型,優於通用 RuntimeExceptionfinal 字段 + 構造器賦值,保證線程安全與領域模型純粹性RuntimeException,控制層統一捕獲轉換為用戶友好提示,避免污染 Service 代碼finally| 維度 | Checked Exception | Unchecked Exception (RuntimeException) |
|---|---|---|
| 編譯器強制 | 必須 try-catch 或 throws | 無強制要求 |
| 適用場景 | 可恢復的業務邏輯(如文件不存在、余額不足) | 編程錯誤、不可恢復系統錯誤、參數非法 |
| 代碼侵入性 | 高(層層 throws) | 低 |
| 推薦策略 | Controller 層捕獲轉換 | Service/DAO 直接拋出,全局異常處理器捕獲 |