Spring Boot 异常处理
Source: Dev.to
请提供您想要翻译的具体内容,我将为您翻译成简体中文。
1. 什么是异常?
异常 = 打破程序正常流程的不期望情况。
异常处理的目标
- 防止程序崩溃
- 控制错误
- 提供适当的消息
2. Java 异常层次结构
Throwable
├── Error
└── Exception
├── RuntimeException (Unchecked)
└── Other Exceptions (Checked)
3. 异常类型(Java 层)
(A) 检查型异常
- 编译时检查
- 必须处理(
try‑catch或throws) - 继承自
Exception(但不是RuntimeException)
示例:IOException、SQLException、ClassNotFoundException、FileNotFoundException、InterruptedException
(B) 未检查型异常
- 运行时出现
- 处理可选
- 继承自
RuntimeException
示例:NullPointerException、ArithmeticException、ArrayIndexOutOfBoundsException、NumberFormatException、IllegalArgumentException
(C) 错误
- JVM / 系统层面的错误
- 通常不处理;自定义
Error是不好的做法
示例:OutOfMemoryError、StackOverflowError
受检异常 vs 未受检异常 规则
extends Exception → Checked Exception
extends RuntimeException → Unchecked Exception
extends Error → Error (avoid)
5. 扩展其他异常
技术上是可能的,但最佳实践是只扩展:
Exception用于受检异常RuntimeException用于未受检异常
避免扩展特定异常,如 NullPointerException、IOException、SQLException 等。
6. try‑catch 与 throws
try‑catch
在异常发生的地点处理它。
try {
FileReader fr = new FileReader("a.txt");
} catch (IOException e) {
System.out.println("File error");
}
throws
将责任委托给调用者。
public void readFile() throws IOException {
FileReader fr = new FileReader("a.txt");
}
规则:已检查的异常必须被捕获或使用 throws 声明。
7. throw vs throws
throw– 手动抛出异常。
throw new IOException("File not found");
throws– 声明方法可能抛出异常。
public void read() throws IOException { }
8. 常见异常含义
ClassNotFoundException– 运行时未找到类。FileNotFoundException– 文件缺失或路径错误。IOException– 文件、网络或流出现问题。SQLException– SQL 数据库错误(MySQL、PostgreSQL、Oracle)。MongoDB 不使用此异常。- MongoDB 等价异常:
MongoException、DuplicateKeyException。 InterruptedException– 线程在sleep、wait或join时被中断。
9. 自定义异常
受检自定义异常
class MyCheckedException extends Exception {
}
未检查自定义异常
class MyUncheckedException extends RuntimeException {
}
10. Java vs Spring Boot 异常处理
Java 级别
try‑catchthrows- 方法级处理
Spring Boot 级别
- 控制器/API 级处理
- 向客户端返回 JSON 响应
- 注解:
@ExceptionHandler、@ControllerAdvice/@RestControllerAdvice
11. Spring Boot 异常处理示例
自定义异常
class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String msg) {
super(msg);
}
}
全局处理器
@RestControllerAdvice
class GlobalExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity handle(UserNotFoundException e) {
return ResponseEntity.status(404).body(e.getMessage());
}
@ExceptionHandler(Exception.class)
public ResponseEntity handleAll(Exception e) {
return ResponseEntity.status(500).body("Server Error");
}
}
控制器
@GetMapping("/user/{id}")
public User getUser(@PathVariable int id) {
return repo.findById(id)
.orElseThrow(() -> new UserNotFoundException("User not found"));
}
12. 关键面试要点
- Checked exception:编译时异常,必须处理。
- Unchecked exception:运行时异常,处理可选。
SQLException只适用于关系型数据库,不适用于 MongoDB。- 自定义异常:继承
Exception以创建受检异常,继承RuntimeException以创建未受检异常。 - Spring Boot 使用
@ControllerAdvice(或@RestControllerAdvice)全局处理 API 错误。
13. 摘要
| 类型 | 继承 | 处理 |
|---|---|---|
| Checked | Exception | try‑catch 或 throws |
| Unchecked | RuntimeException | 可选 |
| Error | Error (avoid) | 避免处理 |