在 java 中,使用异常替代错误码判断的核心做法是:将原本通过返回值(如 -1、null 或布尔值)传递的错误状态,改为在发生错误时抛出特定的 exception 子类,并在调用处使用 try-catch 块进行捕获和处理。这样做可以消除深层嵌套的 if-else 判断,使主流程逻辑更加线性清晰,同时利用异常栈信息提供更丰富的调试上下文。

如何重构返回 null 的查询方法以抛出异常
对于原本返回 null 表示未找到的方法,应改为抛出 NotFoundException。这样调用者无需检查返回值是否为空,直接处理业务数据即可,若未找到则直接中断当前执行流并进入异常处理逻辑。

import java.util.HashMap;
import java.util.Map;
// 自定义异常类
public class NotFoundException extends RuntimeException {
public NotFoundException(String message) {
super(message);
}
}
// 服务类
public class UserService {
private static final Map<String, String> users = new HashMap<>();
static {
users.put("alice", "Alice's Profile");
}
// 重构前:返回 null
// public String getUserProfile(String id) { return users.get(id); }
// 重构后:抛出异常
public String getUserProfile(String id) throws NotFoundException {
String profile = users.get(id);
if (profile == null) {
throw new NotFoundException("User not found: " + id);
}
return profile;
}
}
// 调用示例
public class Main {
public static void main(String[] args) {
UserService service = new UserService();
try {
String profile = service.getUserProfile("bob");
System.out.println(profile);
} catch (NotFoundException e) {
System.err.println("Handled error: " + e.getMessage());
}
}
}
预期输出:
Handled error: User not found: bob
立即学习“Java免费学习笔记(深入)”;
如何处理多条件校验失败并统一抛出业务异常
当存在多个前置条件需要校验时,不再逐个返回错误码,而是定义一个通用的 BusinessException。在方法内部按顺序检查条件,一旦不满足立即抛出异常。这种“快速失败”模式避免了层层返回错误码,且能明确指示出错的具体步骤。

public class BusinessException extends RuntimeException {
public BusinessException(String message) {
super(message);
}
}
public class OrderService {
public void createOrder(String userId, String productId, int quantity) throws BusinessException {
if (userId == null || userId.isEmpty()) {
throw new BusinessException("Invalid user ID");
}
if (productId == null || productId.isEmpty()) {
throw new BusinessException("Invalid product ID");
}
if (quantity <= 0) {
throw new BusinessException("Quantity must be positive");
}
// 正常业务逻辑
System.out.println("Order created for user: " + userId + ", product: " + productId);
}
}
public class Main {
public static void main(String[] args) {
OrderService service = new OrderService();
try {
service.createOrder(null, "prod1", 1);
} catch (BusinessException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
预期输出:
Error: Invalid user ID
当自定义异常未被捕获时会发生什么
如果抛出的自定义异常(如 NotFoundException 或 BusinessException)在调用链顶层未被 try-catch 捕获,JVM 会将其打印到标准错误输出(System.err),并终止当前线程的执行。这确保了错误不会被静默忽略,便于开发阶段快速定位问题,但在生产环境中通常应由全局异常处理器(如 Spring 的 @ControllerAdvice)统一接管并返回友好的 HTTP 响应。


















