java如何自定义异常
自定义异常的基本概念
在Java中,自定义异常是通过继承现有的异常类来实现的。通常可以选择继承Exception(受检异常)或RuntimeException(非受检异常),具体取决于业务需求。
继承Exception类创建受检异常
受检异常需要在方法签名中声明或捕获。以下是一个自定义受检异常的示例:
public class CustomCheckedException extends Exception {
public CustomCheckedException(String message) {
super(message);
}
}
使用时需要在方法中声明或捕获:

public void someMethod() throws CustomCheckedException {
throw new CustomCheckedException("This is a checked exception");
}
继承RuntimeException创建非受检异常
非受检异常不需要在方法签名中声明。以下是一个自定义非受检异常的示例:
public class CustomUncheckedException extends RuntimeException {
public CustomUncheckedException(String message) {
super(message);
}
}
使用时可以直接抛出:

public void someMethod() {
throw new CustomUncheckedException("This is an unchecked exception");
}
添加自定义属性和方法
自定义异常可以扩展功能,添加额外的属性和方法:
public class CustomException extends Exception {
private int errorCode;
public CustomException(String message, int errorCode) {
super(message);
this.errorCode = errorCode;
}
public int getErrorCode() {
return errorCode;
}
}
异常链的使用
可以通过构造函数传递原始异常,形成异常链:
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
public CustomException(String message, Throwable cause) {
super(message, cause);
}
}
最佳实践
为自定义异常提供有意义的名称,通常以"Exception"结尾。包含详细的错误信息和可能的解决方案。考虑异常的可恢复性,决定使用受检还是非受检异常。保持异常类的简洁性,避免包含过多业务逻辑。






