Java / 系统课时
自定义异常与异常抛出
自定义异常与异常抛出
自定义异常用于把“库存不足”“订单状态不允许”等业务失败变成可识别的类型。本课重点区分 throw 与 throws,并通过异常链保留底层失败原因。
学习目标
- 正确使用
throw抛出异常对象、使用throws声明传播类型 - 根据调用方是否必须处理来选择受检或非受检异常
- 在异常转换时通过
cause保留根因
规则与设计
throw 出现在方法体内,后面跟一个异常对象,并立即中断当前正常流程;throws 出现在方法签名中,后面跟异常类型列表,只声明该方法可能把异常交给调用方。
只有调用方确实需要按类型恢复或转换时,才值得新增自定义异常。参数不合法通常使用 IllegalArgumentException;稳定的业务规则失败可使用自定义异常。若选择继承 Exception,调用方必须捕获或继续声明;继承 RuntimeException 则不受编译器强制。
主示例与验证
示例把数量文本解析错误转换为 OrderException,并把原始 NumberFormatException 作为 cause;库存不足也使用同一业务异常类型向上层报告。
java
public class Main {
public static void main(String[] args) {
Inventory inventory = new Inventory("P1001", 5);
try {
int first = parseQuantity("3");
inventory.deduct(first);
int second = parseQuantity("four");
inventory.deduct(second);
} catch (OrderException e) {
System.out.println("处理失败:" + e.getMessage());
System.out.println("底层原因:" +
(e.getCause() == null ? "无" : e.getCause().getClass().getSimpleName()));
}
System.out.println("剩余库存:" + inventory.getStock());
}
static int parseQuantity(String text) throws OrderException {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
// 转换异常时保留 cause,便于日志和排障追踪。
throw new OrderException("数量格式错误:" + text, e);
}
}
}
class OrderException extends Exception {
OrderException(String message) {
super(message);
}
OrderException(String message, Throwable cause) {
super(message, cause);
}
}
class Inventory {
private final String productId;
private int stock;
Inventory(String productId, int stock) {
this.productId = productId;
this.stock = stock;
}
void deduct(int quantity) throws OrderException {
if (quantity <= 0) {
throw new OrderException("扣减数量必须大于 0");
}
if (quantity > stock) {
throw new OrderException(
"商品 " + productId + " 库存不足,需要 " + quantity + ",当前 " + stock);
}
stock -= quantity;
}
int getStock() {
return stock;
}
}运行:
bash
javac Main.java
java Main预期输出:
text
处理失败:数量格式错误:four
底层原因:NumberFormatException
剩余库存:2输出说明第一次扣减已经成功,第二次在解析阶段失败,异常链仍能定位到原始数字格式错误。
边界与排查
异常消息应包含业务标识和关键值,但不得写入密码、令牌或完整隐私数据。不要为每个提示语都创建异常类;只有上层需要分类处理、映射协议状态或执行不同补偿时,类型差异才有价值。
转换底层异常时不要只写 throw new OrderException(e.getMessage()),否则调用栈根因会丢失。也不要先修改对象状态再校验规则,否则抛出异常后可能留下半完成状态。
按自己的节奏,确认真正理解。