定义资源不存在异常需要继承 exception 或 runtimeexception,并添加带消息和原因的构造函数。推荐使用自定义的 resourcenotfoundexception 类,通过 super(message, cause) 传递上下文信息,以便在业务逻辑中精准捕获和处理缺失资源的场景。

如何设计异常的层级结构
将自定义异常放在统一的包下,继承自 BaseException 或直接继承 RuntimeException。这样可以在项目中保持异常处理的一致性,避免混用不同层级的异常类型。

package com.example.exception;
public class BaseException extends RuntimeException {
private final String errorCode;
public BaseException(String errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
public BaseException(String errorCode, String message, Throwable cause) {
super(message, cause);
this.errorCode = errorCode;
}
public String getErrorCode() {
return errorCode;
}
}
上述代码定义了基础异常类,包含错误码和消息。所有自定义异常都应继承此类,确保统一的行为模式。
具体实现资源不存在的异常类
创建 ResourceNotFoundException 类,继承自 BaseException。该类专门用于表示资源(如文件、数据库记录等)未找到的情况。

package com.example.exception;
public class ResourceNotFoundException extends BaseException {
public ResourceNotFoundException(String resourceName, String resourceId) {
super("RES_NOT_FOUND", "Resource not found: " + resourceName + " with id " + resourceId);
}
public ResourceNotFoundException(String resourceName, String resourceId, Throwable cause) {
super("RES_NOT_FOUND", "Resource not found: " + resourceName + " with id " + resourceId, cause);
}
}
该实现提供了两个构造函数,分别支持有无原因的情况。在实际使用中,可以通过抛出此异常来通知调用者资源缺失。
如何在业务代码中触发和捕获该异常
在业务逻辑中,当检测到资源不存在时,直接抛出 ResourceNotFoundException。例如,在查询用户时,如果用户ID不存在,则抛出异常。
public User findUserById(String userId) {
User user = userRepository.findById(userId).orElse(null);
if (user == null) {
throw new ResourceNotFoundException("User", userId);
}
return user;
}
调用方可以使用 try-catch 块捕获该异常,并进行相应的处理,如返回 HTTP 404 状态码或记录日志。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











