Checked vs unchecked

The hierarchy, the original intent, why most modern code prefers unchecked, and the rule that decides it for you.

9 min read🧰 Exceptions, I/O and Reflection

Java is the only mainstream language with checked exceptions, and the debate about whether that was a good idea has run for twenty-five years. You do not need to settle it. You need to know the hierarchy, what each half was intended for, and a rule that tells you which to throw — because the wrong choice spreads throws clauses through code that cannot do anything with them, or hides a failure the caller needed to see.

The hierarchy

plaintext
Throwable
 ├─ Error                      JVM-level: OutOfMemoryError, StackOverflowError — do not catch
 └─ Exception
     ├─ RuntimeException       UNCHECKED: NullPointerException, IllegalArgumentException,
     │                          IllegalStateException, UnsupportedOperationException ...
     └─ (everything else)      CHECKED: IOException, SQLException, InterruptedException ...

A checked exception must be declared in the method's throws clause or caught; the compiler enforces it. An unchecked exception (a RuntimeException or Error) propagates silently. Both unwind the stack the same way at run time; the difference is entirely in what the compiler makes you write.

The original intent

Checked: recoverable conditions the caller should plan for — the file is not there, the connection dropped. Unchecked: programming errors — a null where none was allowed, an index out of range, a state the object was never supposed to be in. The idea was that a caller can do something about a missing file but nothing about a bug.

Why modern code prefers unchecked

In practice, most callers of readConfig() throws IOException cannot do anything about the IOException either. So they wrap it, or declare it, and the throws climbs the call stack through layers that have no interest in files. Lambdas made it worse: Function cannot throw checked exceptions, so every stream over I/O needs a wrapper. Spring wraps SQLException into unchecked DataAccessException for exactly this reason; Hibernate, Jackson and most modern libraries throw unchecked.

The cost of unchecked is that the compiler no longer tells a caller what can fail. Documentation and types (Optional, a sealed Result) take over that job.

The rule

Throw unchecked, unless the immediate caller can reasonably recover and you want the compiler to force them to think about it.

That second case is rare and real: InterruptedException (the caller must restore the interrupt flag or stop), a parse failure in a library whose whole purpose is parsing, a retryable I/O failure at the one boundary that retries. Everywhere else — validation, not-found, illegal state, wrapped infrastructure failures — throw a RuntimeException subclass with a good message.

Standard exceptions to reuse

SituationThrow
Bad argumentIllegalArgumentException
Null argumentNullPointerException via Objects.requireNonNull
Object in wrong state for this callIllegalStateException
Operation not supported hereUnsupportedOperationException
Index problemsIndexOutOfBoundsException
I/O wrapped as uncheckedUncheckedIOException

Use these before inventing your own; a reader knows what they mean.

Catching

  • Catch the narrowest type that you can actually handle. catch (Exception e) at a service layer swallows NullPointerExceptions that were bugs.
  • Never catch and ignore. An empty catch block is a bug silencer. At minimum log with the exception object (not just its message), and say why it is safe to continue.
  • Wrap, do not replace. throw new ServiceException("could not load order " + id, e) keeps the cause. throw new ServiceException("failed") throws away the stack trace that would have explained it.
  • Do not catch Error, except at a top-level boundary to log and die.
  • InterruptedException: either rethrow, or Thread.currentThread().interrupt() before handling. Swallowing it makes the thread un-cancellable.

Multi-catch and rethrow

java
try {
    parse(input);
} catch (NumberFormatException | DateTimeParseException e) {
    throw new ValidationException("bad input: " + input, e);
}

One handler for several types with no common useful supertype. A rethrown exception in a catch (Exception e) block keeps its precise checked type for the throws clause (precise rethrow, Java 7).

Chaining: the cause, and how to read the trace it makes

"Wrap, do not replace" works because every Throwable carries a cause. The constructor takes it — new ServiceException(message, e) — and getCause() returns it, so the translated exception a caller sees still holds the SQLException or IOException that actually happened, all the way down. For an exception type whose constructors take no cause (some old ones in the JDK, some of your own), initCause(e) sets it once, after construction; calling it a second time, or on an exception built with a cause, throws IllegalStateException.

The chain is what the stack trace prints. Read it from the bottom:

one failure, three layersplaintext
in.code10x.OrderService$ServiceException: could not load order 42
    at in.code10x.OrderService.load(OrderService.java:31)
    at in.code10x.OrderController.get(OrderController.java:18)
    ... 12 more
Caused by: org.springframework.dao.DataAccessResourceFailureException: could not get connection
    at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:83)
    ... 14 more
Caused by: java.net.ConnectException: Connection refused
    at java.base/sun.nio.ch.Nio.connect(Native Method)
    ...

The top block is the exception that reached the handler; each Caused by: is one getCause() deeper; the last one is the root cause, and it is usually the only line that says what went wrong. ... 12 more is not lost information — those frames are identical to the enclosing trace and the printer elides them. When you need the root in code, walk it: while (e.getCause() != null) e = e.getCause(); (Spring's NestedExceptionUtils.getMostSpecificCause and Guava's Throwables.getRootCause do this, with a guard against a cycle). A cause is different from a suppressed exception, which the try-with-resources lesson covers: a cause is why this exception happened, a suppressed one is another failure that happened while this one was in flight.

Exceptions are not control flow

Throwing is expensive — filling in the stack trace walks every frame — and a method that throws on an expected outcome ("no user with that email" on a login form) is slow and lies about what happened. Return Optional, a boolean, or a sealed result for outcomes that are part of the normal path. Throw for things that should not happen or that the caller cannot continue past.

Under the hood: the JVM does not know what a checked exception is

Everything in this lesson so far is a rule the compiler enforces. The JVM itself has no such rule, and no such concept.

The instruction that throws an exception is athrow (JVM Specification §6.5): it pops an object reference off the stack and throws it. There is one athrow, used for every exception, checked or not — the bytecode carries no flag that says "this one needed a throws clause." A method's exception table (used to find a matching catch) is matched by instanceof-style class checks against the thrown object's actual runtime class, never by whether that class happened to extend RuntimeException.

A class file does record a method's declared checked exceptions — the Exceptions attribute (§4.7.5) — but it is informational only. It exists so a separately compiled caller (a different .java file, possibly compiled later) can be checked by javac against what a method promises to throw, and so reflection can report it (Method.getExceptionTypes()). Neither the bytecode verifier nor the runtime's exception dispatch reads it. Nothing stops a method whose Exceptions attribute is empty from actually throwing a checked exception at run time — javac just does not let you write that method directly.

That gap is exploitable, and doing it once makes the "compile-time-only" claim concrete rather than theoretical:

java
class Sneaky {
    @SuppressWarnings("unchecked")
    static <T extends Throwable> void throwAs(Throwable t) throws T { throw (T) t; }
}

throwAs declares throws T — a type parameter, not a fixed type. At a call site with nothing constraining T, javac infers it as RuntimeException, because generics are erased and an unconstrained checked-exception type parameter defaults to an unchecked one. The method compiles; every caller compiles, with no throws IOException in sight anywhere. At run time, erasure has already happened — the cast (T) t is a no-op — and whatever Throwable was actually passed in is thrown via the same athrow as anything else, including a genuine IOException. This is the "sneaky throws" technique Lombok's @SneakyThrows is built on.

Try it yourself

java
class Sneaky {
    @SuppressWarnings("unchecked")
    static <T extends Throwable> void throwAs(Throwable t) throws T { throw (T) t; }
}
Runnable r = () -> Sneaky.throwAs(new java.io.IOException("disk gone"));
try {
    r.run();
} catch (Exception e) {
    System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());
}

Predict before running: does this even compile?

Runnable.run() declares no checked exceptions, and the lambda's body calls Sneaky.throwAs with a real IOException — a checked type. Before running it: does javac reject the lambda, the way it would reject () -> { throw new IOException("x"); } assigned to a Runnable? If it compiles, what actually gets thrown when r.run() executes?

It compiles, and a real IOException comes out of a method that declares nothing

It compiles because T in throwAs is inferred at the call site with no constraint forcing it to be IOException — javac picks the unchecked default, RuntimeException, so as far as the lambda's checked-exception compatibility with Runnable.run() is concerned, throwAs looks like it throws nothing checked. That inference is the entire trick.

At run time, the object actually thrown is the real IOException passed in — erasure does not change what object flows through athrow, only what the compiler believed about it. So r.run() throws a genuine checked IOException out of a method (Runnable.run()) whose signature does not, and never could, declare it. Catching it needs catch (Exception e) or catch (IOException e) at a point where the compiler can be convinced it is reachable — catch (Exception e) always works, since Java never restricts what a catch clause of a broad-enough type may catch. This is the sharpest possible demonstration that checked-ness is a compile-time bookkeeping exercise: the exact same IOException, same message, same stack trace, flows through code the compiler was certain could never see one.

Misconceptions

  • "The JVM enforces checked exceptions; javac just catches the mistake earlier." No — the enforcement is entirely javac's. The class file's Exceptions attribute is advisory, read by tools and by javac itself when checking a separately compiled caller, but never consulted by the bytecode verifier or by exception dispatch at run time.
  • "You cannot throw a checked exception from a lambda — it's a JVM restriction on functional interfaces." It is a compile-time compatibility check against the functional interface's single abstract method, nothing more. The predict exercise above throws a real checked exception through a Runnable at run time; the JVM never notices anything unusual, because from athrow's point of view nothing is.

Sources

  • The Java Virtual Machine Specification, SE 21 — §6.5 (athrow) and §4.7.5 (The Exceptions Attribute).
  • The Java Language Specification, SE 21 — §11.2 (Compile-Time Checking of Exceptions).
  • Joshua Bloch, Effective Java, 3rd ed. — Item 71, "Avoid unnecessary use of checked exceptions".
Progress is saved on this device and to your account when signed in.