M4RKYU.SYSEdition 2027
Skip to content
LOCZH/安大略 · 加拿大/▸logs · understanding the throw and throws keywords in java 5fjd待机OK/--:--:--EST
M4M4RK_YUportfolio
  • 创作创作
    创作Overview
    • 作品精选案例与项目记录
    • 游戏可玩原型与游戏开发日志
  • 影像影像
    影像Overview
    • 照片影像合集与视觉实验
    • 商店印刷品、海报和限量物件
  • 写作写作
    写作Overview
    • 博客长篇开发日志与现场笔记
    • 笔记短观察、链接与代码片段
  • 资源资源
    资源Overview
    • 工具38 款浏览器内开发工具
    • 链接每日使用的开发与设计书签
  • 关于关于
  • 联系联系
EN

同步 · dev.to / @markyu

Java throw vs throws: The Exception Bug They Reveal

A practical Java exception handling guide explaining throw, throws, checked exceptions, runtime exceptions, and API boundary decisions.

发布日期
May 22 '24
·
阅读时长
2 min read
·
点赞
5
javabackendprogrammingbeginners
在 dev.to 查看

本页目录

  • The Short Version
  • throw: Fail Here
  • throws: Caller Must Deal With It
  • Checked vs Runtime Exceptions
  • Do Not Swallow Exceptions
  • API Boundary Example
  • Final Thought

throw and throws are easy to memorize and still easy to misuse.

The real difference is not grammar.

throw is the moment you raise an exception. throws is the method contract that warns callers an exception may escape.

The Short Version

KeywordWhere it appearsWhat it means
throwinside method bodyraise this exception now
throwsmethod signaturethis method may pass this exception upward

throw: Fail Here

public User findUser(String id) {
    if (id == null || id.isBlank()) {
        throw new IllegalArgumentException("User id is required");
    }

    return repository.findById(id);
}

This is a direct failure.

I like this for invalid programmer input or impossible states. Do not let bad data travel deeper into the system.

throws: Caller Must Deal With It

public String readConfig(String path) throws IOException {
    return Files.readString(Path.of(path));
}

The method is saying:

I might fail with IOException, and I am not handling it here.

Caller:

try {
    String config = readConfig("app.yml");
} catch (IOException e) {
    log.error("Failed to read config", e);
}

Checked vs Runtime Exceptions

Checked exceptions must be handled or declared:

public void load() throws IOException {
    Files.readString(Path.of("app.yml"));
}

Runtime exceptions do not need throws:

throw new IllegalArgumentException("Bad request");

My rough rule:

  • Use checked exceptions when the caller can reasonably recover.
  • Use runtime exceptions for programming mistakes or invalid state.

Do Not Swallow Exceptions

This is the code smell:

try {
    sendEmail();
} catch (Exception e) {
    // ignore
}

If the email matters, ignoring the exception lies to the system.

At least log it or return a failure result:

try {
    sendEmail();
} catch (MailException e) {
    log.warn("Email send failed for user {}", userId, e);
}

API Boundary Example

Inside infrastructure code:

public User loadUser(String id) throws SQLException {
    // database call
}

At the service boundary, I usually translate it:

public User getUser(String id) {
    try {
        return userDao.loadUser(id);
    } catch (SQLException e) {
        throw new UserLookupException("Failed to load user " + id, e);
    }
}

This keeps SQL details from leaking everywhere.

Final Thought

throw is an action. throws is a warning label.

Good exception design is mostly about choosing where a failure should be handled and where it should be translated.

Do you prefer checked exceptions or runtime exceptions in Java service code?

相关阅读

Java final, finally, finalize: Three Bugs They Prevent

A practical Java explanation of final, finally, and finalize using real failure modes instead of memorized definitions.

java

Java BeanUtils Copying: Convenient, but Not Free

A practical Java guide to BeanUtils, shallow copy pitfalls, reflection overhead, and when MapStruct or manual mapping is a better choice.

java

Frontend Linear Data Structures Deep Dive: Arrays, Stacks, Queues, and Linked Lists

The Big Picture Before diving into stacks, queues, and linked lists, it helps to know...

computerscience

原文发布

本文首发于 dev.to,评论与点赞保留在原站。

在 dev.to 继续阅读
上一篇JavaScript Memory Leaks Usually Start With One ReferenceA practical JavaScript memory guide covering stack, heap, garbage collection, closures, event listeners, timers, and leak debugging.
返回全部文章
下一篇Java final, finally, finalize: Three Bugs They PreventA practical Java explanation of final, finally, and finalize using real failure modes instead of memorized definitions.
返回档案
M4RKYUM4RKYUM4RKYUM4RKYUM4RKYUM4RKYUM4RKYUM4RKYU
始于 2024
ZhenXiao Mark YuZhenXiao Mark Yu
联系

看到什么有意思的?和我聊聊。

这是一个作品集,不是服务 · 但每一条留言我都会看 — 如果哪里让你有所触动,或者只想打个招呼,欢迎写信过来。

开启对话
频道开放

随时打个招呼 · 2026

--:--:--EST加拿大 安大略
  • 邮件
  • GitHub
  • dev.to
  • 领英
  • 推特 / X
  • Instagram
  • Facebook
  • YouTube
  • CodePen
  • Spotify
  • Snapchat

订阅

偶尔收到一封简讯

来自 m4rkyu.com 的笔记与日志——简短、标注日期、没有杂音。随时可退订。

作品

线上发布、游戏作品与视觉档案。

  • 项目
  • 游戏
  • 档案
  • 日志

资源

每日好用的工具与个人收藏的链接库。

  • 搜索
  • 最新
  • 工具
  • 链接
  • 笔记
  • 主题
  • 商店
RSSJSON Feed

工作室

背景、联系方式以及合作渠道。

  • 关于
  • 联系
  • 更新日志
  • 技术说明
  • 简历筹备中

社交

在常去的平台上找到我。

  • GitHub
  • dev.to
  • 领英
  • 推特 / X
  • Instagram
  • Facebook
  • YouTube
  • CodePen
  • Spotify
  • Snapchat
  • 邮件
© 2026 ZhenXiao Mark Yumarkyu0615@gmail.com
  • 邮件
  • GitHub
  • dev.to
  • 领英
  • 推特 / X
  • Instagram
  • Facebook
  • YouTube
  • CodePen
  • Spotify
  • Snapchat
隐私条款由 Next.js 16 · React 19 · Tailwind 4 构建