M4RKYU.SYSEdition 2027
Skip to content
LOCEN/Ontario · CA/▸logs · understanding the throw and throws keywords in java 5fjdStandbyOK/--:--:--EST
M4M4RK_YUportfolio
  • BuildBuild
    BuildOverview
    • WorkSelected case studies and write-ups
    • GamesPlayable prototypes and game-dev logs
  • GalleryGallery
    GalleryOverview
    • PhotosPhoto collections and visual experiments
    • ShopPrints, posters, and one-off objects
  • WritingWriting
    WritingOverview
    • BlogLong-form devlogs and field notes
    • NotesShort observations, links, snippets
  • ResourcesResources
    ResourcesOverview
    • Tools38 in-browser developer utilities
    • LinksDaily-use dev and design bookmarks
  • AboutAbout
  • ContactContact
中文

syndicated · 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.

Published
May 22 '24
·
Reading time
2 min read
·
Reactions
5
javabackendprogrammingbeginners
View on dev.to

On this page

  • 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?

Related reading

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

originally published

This post first ran on dev.to. Comments and reactions live there.

Continue on dev.to
PreviousJavaScript Memory Leaks Usually Start With One ReferenceA practical JavaScript memory guide covering stack, heap, garbage collection, closures, event listeners, timers, and leak debugging.
Back to all posts
NextJava final, finally, finalize: Three Bugs They PreventA practical Java explanation of final, finally, and finalize using real failure modes instead of memorized definitions.
Back to archive
M4RKYUM4RKYUM4RKYUM4RKYUM4RKYUM4RKYUM4RKYUM4RKYU
Crafted since 2024
ZhenXiao Mark YuZhenXiao Mark Yu
get in touch

Saw something here?Tell me about it.

It's a portfolio, not a service · but I read every note — drop a line if anything here resonated, or just to say hi.

Start a conversation
open channel

say hi anytime · 2026

--:--:--ESTOntario, Canada
  • Email
  • GitHub
  • dev.to
  • LinkedIn
  • Twitter / X
  • Instagram
  • Facebook
  • YouTube
  • CodePen
  • Spotify
  • Snapchat

Newsletter

Get the occasional dispatch

Notes and logs from m4rkyu.com — short, dated, no noise. Unsubscribe anytime.

Work

Production builds, games, and visual archives.

  • Projects
  • Games
  • Archive
  • Logs

Resources

Daily-use tools and a personal link library.

  • Search
  • Latest
  • Tools
  • Links
  • Notes
  • Topics
  • Shop
RSSJSON feed

Studio

Background, contact, and channels for collaboration.

  • About
  • Contact
  • Changelog
  • Colophon
  • Resumepending

Socials

Find me on the usual feeds.

  • GitHub
  • dev.to
  • LinkedIn
  • Twitter / X
  • Instagram
  • Facebook
  • YouTube
  • CodePen
  • Spotify
  • Snapchat
  • Email
© 2026 ZhenXiao Mark Yumarkyu0615@gmail.com
  • Email
  • GitHub
  • dev.to
  • LinkedIn
  • Twitter / X
  • Instagram
  • Facebook
  • YouTube
  • CodePen
  • Spotify
  • Snapchat
PrivacyTermsBuilt with Next.js 16 · React 19 · Tailwind 4