java如何自定义异常
自定义异常的基本概念
在Java中,自定义异常是通过继承现有的异常类来实现的。通常选择继承Exception(受检异常)或RuntimeException(非受检异常)。自定义异常允许开发者根据业务需求定义特定的错误类型。
继承Exception类
创建一个受检异常(Checked Exception),需要处理或声明抛出。示例代码:

public class CustomCheckedException extends Exception {
public CustomCheckedException(String message) {
super(message);
}
}
继承RuntimeException类
创建一个非受检异常(Unchecked Exception),不强制处理。示例代码:
public class CustomUncheckedException extends RuntimeException {
public CustomUncheckedException(String message) {
super(message);
}
}
添加自定义属性和方法
可以在自定义异常中添加额外属性或方法,增强异常信息的丰富性。示例代码:

public class CustomException extends Exception {
private int errorCode;
public CustomException(String message, int errorCode) {
super(message);
this.errorCode = errorCode;
}
public int getErrorCode() {
return errorCode;
}
}
使用自定义异常
在代码中抛出自定义异常,可以通过throw关键字实现。示例代码:
public class Example {
public void checkValue(int value) throws CustomCheckedException {
if (value < 0) {
throw new CustomCheckedException("Value cannot be negative");
}
}
}
捕获和处理自定义异常
使用try-catch块捕获并处理自定义异常。示例代码:
public class Example {
public static void main(String[] args) {
Example example = new Example();
try {
example.checkValue(-1);
} catch (CustomCheckedException e) {
System.out.println("Caught exception: " + e.getMessage());
}
}
}
最佳实践
- 自定义异常名称应明确描述异常类型,通常以
Exception结尾。 - 提供多个构造方法,支持不同的异常信息传递方式。
- 避免过度使用自定义异常,优先考虑Java内置异常是否满足需求。
- 为自定义异常添加文档注释,说明异常的用途和触发条件。




