在 Java 中,throws 用于方法声明上,表示该方法可能抛出哪些受检异常(checked exception),交给调用者处理。合理使用 throws 是写出健壮、可维护代码的重要一环。下面从原则、常见误区和最佳实践三个层面来说明。
throws Exception如果一个异常在当前方法中无法合理处理,才使用 throws。
public void saveUser(User user) throws IOException {
Files.write(path, user.toString().getBytes());
}
✅ 合理:IO 异常不是 saveUser 能处理的
❌ 不合理:
public void saveUser(User user) throws Exception {
...
}
throws Exception(非常关键)throws Exception 的问题:
❌ 不推荐:
public void process() throws Exception {
...
}
✅ 推荐:
public void process() throws IOException, SQLException {
...
}
| 类型 | 是否 throws | 使用场景 |
|---|---|---|
| Checked Exception | ✅ 需要 | 调用者必须处理 |
| RuntimeException | ❌ 不需要 | 程序 bug / 逻辑错误 |
✅ 示例:
public void divide(int a, int b) {
if (b == 0) {
throw new IllegalArgumentException("除数不能为 0");
}
}
✅ 不需要 throws
底层 throws,高层 catch
// DAO
public User findById(Long id) throws SQLException {
...
}
// Service
public User getUser(Long id) {
try {
return dao.findById(id);
} catch (SQLException e) {
throw new ServiceException("查询用户失败", e);
}
}
✅ 好处:
❌ 错误示例:
public void read() throws IOException {
try {
...
} catch (IOException e) {
// 什么都不做
}
}
✅ 正确做法:
当底层异常不适合暴露给上层时:
throw new BusinessException("用户保存失败", e);
✅ 保留原始异常(cause) ✅ 提高可读性
throws 是 API 的一部分:
✅ 建议:
| 误区 | 说明 |
|---|---|
throws Exception |
太宽泛,失去意义 |
| 每个方法都 throws | 异常传播失控 |
| 用 throws 代替 if 校验 | 逻辑错误 |
| 捕获后不处理 | 隐藏 bug |
| main 方法直接 throws | 程序直接崩溃 |
throws不是用来“甩锅”的,而是用来“明确责任边界”的。
如果你愿意,我可以:
throwsthrows vs try-catch免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。