Skip to content

Lesson 5 of 14 · 18m

Exceptions Are a Type System for Failure

Checked vs. unchecked vs. Error, try-with-resources and suppressed exceptions, and the boundary discipline that keeps failures diagnosable.

A production endpoint returns 500 with a stack trace that ends at NullPointerException: Cannot invoke ... inside a mapper — and the actual cause, a SocketTimeoutException three calls deeper, was eaten by an empty catch block someone left as a TODO eighteen months ago. Exception handling is where Java codebases quietly decide whether failures will be diagnosable or silent. This is the taxonomy that decides.

Checked, unchecked, Error — and why the distinction matters

Java's checked-exception experiment — IOException, SQLException must be caught or declared — was designed to force callers to confront failure. Kotlin, Scala, and every other JVM language dropped the idea entirely; it survives in Java's core APIs and creates friction where flows cross layers. RuntimeException and its subclasses are unchecked: NullPointerException, IllegalArgumentException, IllegalStateException. The convention that survived: checked for recoverable, environmental failures (I/O, timeouts, deadlocks); unchecked for programming errors — a contract violation shouldn't be caught, it should be fixed.

Then there's Error — OutOfMemoryError, StackOverflowError — which you do not catch. Ever. catch (Throwable t) swallows an OOM mid-allocation and leaves a half-alive process; the exception handler itself can't allocate the frame it needs. Catch Exception, not Throwable, and let Error kill the thread.

The mechanics people get wrong

try-with-resources (Java 7) calls AutoCloseable.close() even when the block throws — this is the entire fix for leaked file handles, connections, and streams:

try (var conn = ds.getConnection();
     var ps = conn.prepareStatement(SQL)) {
    ps.setString(1, id);
    return ps.executeQuery();
}

When close() throws while the block is already throwing, the close exception is added as suppressed — read it with t.getSuppressed(), because the exception you saw in the log may be the suppressor, not the cause. This is also why finally { conn.close(); } by hand is wrong: it masks the original failure.

fillInStackTrace() captures the call stack at construction — a real walk, microsecond-cheap per throw but expensive in a hot loop. That's the concrete reason exceptions are for failure, not flow control: parsing a million rows with try { Integer.parseInt } catch (NumberFormatException) { skip } burns measurable CPU on stack traces nobody reads. Use Optional or a validator on hot paths; reserve exceptions for the exceptional.

The boundary discipline

An exception should be caught once, at the layer that can act on it — and translated to something the caller understands. A servlet filter turns your OrderNotFoundException into a 404; a repository turns SQLException into your domain's DataAccessException. Spring's org.springframework.dao hierarchy does exactly this — it converts checked, driver-specific SQLExceptions into a semantic unchecked tree so business code never sees PSQLException leak through three layers. The opposite pattern — catching, logging, and re-throwing raw — doubles your log noise and hides the real origin.

Wrap the chain, don't break it: throw new OrderException("enrich failed", e) keeps getCause() intact. log.error("failed") then throw e loses the context that makes incidents debuggable.

CompletableFuture.join() wraps checked causes in CompletionException — unwrap e.getCause() at the boundary or every async failure looks like a completion bug.

Try this

Take a service that logs and rethrows three times on the way up; collapse it to one catch at the controller boundary with the cause chain preserved. Then write a try-with-resources where close() throws and print getSuppressed() — once you've seen suppression, the finally version reads as broken.

Pitfalls

  • catch (Exception e) {} is a silent killer — it converts every failure into a later, stranger failure. Log it, translate it, or declare it.
  • finally returning a value swallows the block's own return and any in-flight exception.
  • Error is not your problem; catching it makes it your problem permanently.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.