异常处理是软件开发中保证系统健壮性、可维护性和可观测性的关键环节。下面从设计原则、编码实践、常见反模式、不同语言要点、运维与观测几个层面,系统总结异常处理的最佳实践。
try {
doSomething();
} catch (Exception e) {
// ❌ 错误示例
}
至少应记录日志或重新抛出。
// ❌
throw new Exception("error");
// ✅
throw new IllegalArgumentException("userId must not be null");
throw new RuntimeException(
"Failed to update order, orderId=" + orderId
);
catch (SQLException e) {
throw new OrderSaveException("save order failed", e);
}
// ❌
finally {
return result; // 会掩盖异常
}
try (InputStream in = new FileInputStream(file)) {
...
}
{
"code": "ORDER_NOT_FOUND",
"message": "订单不存在",
"traceId": "abc123"
}
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BusinessException.class)
public Result handle(BusinessException e) {
return Result.fail(e.getCode(), e.getMessage());
}
}
| 反模式 | 问题 |
|---|---|
| 捕获 Exception 后忽略 | 隐藏 bug |
| 用异常做流程控制 | 性能差、可读性差 |
| 在每个方法都 try-catch | 代码臃肿 |
| 把异常当返回值 | 破坏语义 |
| 暴露底层异常给前端 | 安全风险 |
如果你有具体语言(Java / Python / Go / JS)或使用场景(Web / 微服务 / 脚本),我可以给你更针对性的异常规范或模板。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。