Skip to content

项目异常捕获、异常类和使用

异常捕获

局部捕获

try {
    // 可能发生异常的代码
    int result = 10 / 0;
} catch (ArithmeticException e) {
    log.error("出现异常:", e); // 记录日志
    throw e; // 再抛出供上层调用者处理
}

一般捕获异常后,会进行日志记录,写入日志文件或告警系统。

全局捕获

@RestControllerAdvice
public class GlobalExceptionHandler {
    
    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(Exception e) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("系统错误:" + e.getMessage());
    }

    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<String> handleBusinessException(BusinessException e) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("业务异常:" + e.getMessage());
    }
}

异常类设计

Java 语言中的异常定义分类:

  • 检查型异常(Checked Exception): 必须显式处理(throws 或 try-catch),如 IOException 等
  • 运行时异常(Unchecked Exception): 是继承自 RuntimeException 的异常,程序可以不必捕获,默认会向上抛出

在项目开发的时候,我们一般会将异常分为两类:

  • 业务异常: 适合使用 RuntimeException(可以继承)
  • 系统异常: 适合继承 Exception(检查型)

实际的项目中使用. to be contined...