在 Java 中,自定义异常通常是指创建自己的异常类,用于表达业务或系统中特定的错误情况。下面从基本用法 → 常见写法 → 最佳实践逐步说明。
适用于调用者必须处理的异常。
public class BusinessException extends Exception {
public BusinessException(String message) {
super(message);
}
}
使用:
throw new BusinessException("余额不足");
适用于程序逻辑错误 / 业务校验失败(更常用)。
public class BusinessException extends RuntimeException {
public BusinessException(String message) {
super(message);
}
}
public class BusinessException extends RuntimeException {
private final String code;
public BusinessException(String code, String message) {
super(message);
this.code = code;
}
public String getCode() {
return code;
}
}
使用示例:
throw new BusinessException("1001", "用户不存在");
public class BusinessException extends RuntimeException {
public BusinessException(String message, Throwable cause) {
super(message, cause);
}
}
public enum ErrorCode {
USER_NOT_FOUND("1001", "用户不存在"),
BALANCE_NOT_ENOUGH("1002", "余额不足");
private final String code;
private final String message;
ErrorCode(String code, String message) {
this.code = code;
this.message = message;
}
public String getCode() { return code; }
public String getMessage() { return message; }
}
public class BusinessException extends RuntimeException {
private final String code;
public BusinessException(ErrorCode errorCode) {
super(errorCode.getMessage());
this.code = errorCode.getCode();
}
}
✅ 适合使用自定义异常:
❌ 不适合:
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BusinessException.class)
public ResponseEntity<?> handle(BusinessException e) {
return ResponseEntity
.status(400)
.body(Map.of("code", e.getCode(), "msg", e.getMessage()));
}
}
自定义异常 = 继承 Exception / RuntimeException + 合理构造方法 + 明确语义
如果你有具体场景(如:Spring Boot、支付系统、校验失败),我可以帮你设计一个更合适的异常体系。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。