java 如何定义异常
定义自定义异常
在Java中,自定义异常通常通过继承Exception类或其子类(如RuntimeException)实现。以下是两种常见场景的定义方式:
检查型异常(Checked Exception)
需显式处理或声明抛出,继承自Exception类:
public class CustomCheckedException extends Exception {
public CustomCheckedException(String message) {
super(message);
}
}
非检查型异常(Unchecked Exception)
通常继承RuntimeException,不强制处理:
public class CustomUncheckedException extends RuntimeException {
public CustomUncheckedException(String message, Throwable cause) {
super(message, cause);
}
}
异常构造方法设计
建议至少提供以下两种构造方法:
public class BusinessException extends RuntimeException {
// 基础构造
public BusinessException(String message) {
super(message);
}
// 带原因链的构造
public BusinessException(String message, Throwable cause) {
super(message, cause);
}
}
异常使用场景
检查型异常适用于可预见的异常情况(如文件不存在),要求调用方必须处理:
public void processFile() throws CustomCheckedException {
if (!file.exists()) {
throw new CustomCheckedException("File not found");
}
}
非检查型异常适用于程序逻辑错误(如参数校验):
public void validateInput(int value) {
if (value < 0) {
throw new CustomUncheckedException("Negative value not allowed");
}
}
最佳实践
- 异常命名应使用
Exception后缀 - 优先使用标准异常(如
IllegalArgumentException)而非自定义异常 - 避免在异常中保存可变状态
- 重写
toString()方法可提供更友好的错误信息 - 考虑实现
Serializable接口保证异常可序列化
示例包含额外信息的异常:
public class PaymentException extends RuntimeException {
private final String transactionId;
public PaymentException(String message, String transactionId) {
super(message);
this.transactionId = transactionId;
}
public String getTransactionId() {
return transactionId;
}
}






