Skip to content
Tutorials Center
My learning

Topics

Lesson 75 of 201 ยท Exceptions

Exception Handling Best Practices

Handle Java exceptions like a professional - never swallow them, catch specific types, fail fast, avoid finally traps, choose Optional or exceptions, log once.

Knowing the syntax of try, catch, throw and throws is the easy part. The hard part is deciding what to do when something goes wrong: catch it here or let it travel? Wrap it, log it, retry it, or turn it into an empty result? Bad answers to those questions produce the worst kind of bug: a program that fails silently, hours away from the line that caused it.

This lesson collects the habits experienced Java developers follow. Each one comes with a runnable example of what goes wrong without it. You should already know the mechanics from Exceptions and try-catch, Throwing Exceptions, Custom Exceptions and try-with-resources.

Never swallow an exception

An empty catch block is the single most expensive habit in Java. It turns a loud, precise failure into a quiet wrong answer:

Java
try {
    timeout = Integer.parseInt(text);
} catch (NumberFormatException e) {
    // ignore
}

The program keeps running with whatever timeout held before, and nobody learns that the configuration was broken. Compare three ways to read a list of settings:

Java Swallowing vs handling vs propagating

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The third block fails on purpose: it ends with an IllegalStateException whose message names the setting, followed by Caused by: java.lang.NumberFormatException: For input string: "30s". That stack trace is what you want to see when the configuration is wrong.

If you truly have nothing to do in a catch block (it happens, for example when closing something that is already broken), say so in code: name the variable ignored and write a comment explaining why ignoring is safe. A reader should never have to guess whether an empty block was deliberate.

Catch specific exceptions, at the right level

catch (Exception e) catches everything, including bugs you never anticipated: a NullPointerException from a typo, an ArrayIndexOutOfBoundsException from an off-by-one error. Those are then "handled" by code that was written for a completely different problem.

Catch the narrowest type you can actually do something about:

Java
try {
    return Files.readString(path);
} catch (NoSuchFileException e) {          // a specific, expected situation
    return "";                              // missing file means "no notes yet"
}
// any other IOException still propagates to the caller

Two related rules:

  • Don't catch Throwable or Error. OutOfMemoryError and StackOverflowError mean the JVM is in trouble; your recovery code will probably fail too.
  • Catching broadly is fine at a boundary. The top of a request handler, a scheduled task or main is the right place for one catch (Exception e) that logs the failure and returns an error response, so a single bad request doesn't kill the whole server. One broad catch at the top, specific catches below.

Where should the specific catches go? Handle an exception at the level that knows what to do about it. A low-level parsePrice method can't know whether a bad price should skip the row, stop the import or ask the user; the import loop can. So low-level code usually throws, and higher-level code decides.

Fail fast with clear messages

The earlier a problem is detected, the cheaper it is to fix. A method that accepts garbage and fails three calls later produces a stack trace pointing at the wrong place. Check arguments at the start of public methods and constructors, and throw standard exceptions with messages that include the bad value:

Java Validating arguments up front

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Prefer the standard exceptions before inventing your own; every Java developer already knows what they mean:

Exception Throw it when
IllegalArgumentException an argument has a bad value (negative size, empty name)
NullPointerException (via Objects.requireNonNull) an argument is null but must not be
IllegalStateException the object is in the wrong state for this call (reading from a closed reader)
IndexOutOfBoundsException (via Objects.checkIndex) an index is outside a valid range
UnsupportedOperationException the operation isn't supported at all (adding to an immutable list)
NoSuchElementException someone asks for an element that isn't there

A good message answers "what was expected and what did we get?" "percent must be 1-90, was 95" beats "invalid input" every time. Never put passwords, tokens or personal data in messages; they end up in logs.

Keep the cause when you wrap

When you translate a low-level exception into a higher-level one (see Custom Exceptions), always pass the original as the cause. Without it, the stack trace of the real failure is gone:

Java
} catch (SQLException e) {
    throw new OrderStoreException("Could not save order " + id);      // BAD: cause lost
}

} catch (SQLException e) {
    throw new OrderStoreException("Could not save order " + id, e);   // GOOD: "Caused by: ..."
}

The same applies to throw new RuntimeException(e.getMessage()): it keeps the text but throws away the type and stack trace. Pass e itself.

The traps in finally

finally runs whether the try block finished normally, returned or threw. That makes it the place for cleanup, and a dangerous place for anything else. Two traps catch even experienced developers:

Java How finally can hide an exception

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

  1. return in finally swallows the exception. The method returns -1 and "the real problem" vanishes. The compiler only warns with -Xlint:finally, which is why the example suppresses that warning. Never return from finally.
  2. An exception thrown in finally replaces the original. The caller sees "cleanup failed" and never learns what actually went wrong.

The third method shows the fix: try-with-resources. When both the body and close() fail, it keeps the original exception and attaches the cleanup failure as a suppressed exception. Use try-with-resources for everything that implements AutoCloseable, and keep finally for small, non-throwing cleanup such as resetting a flag or unlocking a lock.

Exceptions, return values or Optional?

Exceptions are for exceptional situations: things the normal flow doesn't expect. When "not found" or "invalid" is a perfectly ordinary outcome, an exception is the wrong tool. It's slower (building a stack trace costs far more than returning a value), and it forces every caller into try/catch for an everyday case.

Ask: "Would a caller be surprised by this outcome?"

  • Absence is normal (looking up a user by email, finding the first matching item): return an Optional.
  • The caller must choose between several outcomes: return a small result type, such as a sealed interface of records, and let a switch handle each case.
  • A precondition was violated or the world broke (bad argument, disk full, network down): throw.
Java Optional for normal absence, exceptions for broken input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice that the exhaustive switch over the sealed result makes it impossible to forget a case, something no catch block can promise. And don't go the other way and return null or magic values like -1 to signal errors: callers forget to check, and the failure moves somewhere else.

Never use exceptions for ordinary control flow, such as ending a loop by waiting for ArrayIndexOutOfBoundsException. It's slow, hard to read, and it hides real bugs of the same type.

Checked or unchecked?

Java's two families of exceptions (see Throwing Exceptions) suggest a guideline:

  • Checked (extends Exception): the caller can reasonably recover and should be forced to think about it. A missing file the user picked, a payment that was declined.
  • Unchecked (extends RuntimeException): programming errors and failures callers can't do much about. Bad arguments, broken invariants, a misconfigured system.

Modern Java code leans toward unchecked exceptions, partly because checked exceptions don't work well with lambdas and streams: Function can't throw IOException. When a checked exception has to pass through a lambda, wrap it in UncheckedIOException (or your own unchecked type) with the original as the cause. Either way, document what a method throws with @throws in its Javadoc, including unchecked exceptions callers should know about.

Log once, at the right place

A classic anti-pattern is "log and rethrow" at every level:

Java
} catch (IOException e) {
    log.error("Failed to load", e);   // logged here...
    throw new ReportException("Failed to load report", e);   // ...and again by every caller
}

The same failure shows up four times in the log, with four stack traces, and nobody knows which one matters. The rule: either handle it (and log if useful) or rethrow it (with context), not both. Typically, the boundary that finally handles the exception logs it once, with the full chain of causes.

Use a logger rather than printStackTrace(). A logger adds timestamps and levels, can be filtered and routed to files, and keeps errors out of normal output. The JDK ships java.util.logging, covered in Logging; real applications usually use SLF4J with Logback or Log4j 2. Pass the exception object as the last argument so the stack trace is recorded:

Java Logging the exception once at the boundary

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The static block sets a compact log format so the output stays readable here; normally you configure that in a properties file. The warning, with its stack trace and Caused by: section, goes to standard error.

A short checklist

  • Never leave a catch block empty without a comment explaining why.
  • Catch the most specific type you can handle; catch broadly only at boundaries.
  • Validate arguments early, with standard exceptions and messages that include the bad value.
  • Always pass the original exception as the cause when wrapping.
  • Never return or throw from finally; use try-with-resources for cleanup.
  • Use Optional or result types for normal outcomes, exceptions for broken ones.
  • When you catch InterruptedException, restore the flag with Thread.currentThread().interrupt() unless you rethrow it (see Thread Lifecycle and Priorities).
  • Log once, where the exception is handled, with the exception object attached.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does static int f() { try { throw new RuntimeException("x"); } finally { return 7; } } do when called?

    A return in finally completes the method normally, discarding the pending exception. That's why you should never return from finally.
  2. 2. A method looks up a customer by email, and "no such customer" happens many times a day. What should it return?

    Absence is an ordinary outcome here, so Optional makes it explicit and cheap. null is easy to forget, and an exception makes every caller write try/catch for a normal case.
  3. 3. Which wrapping code keeps the most information about the original failure?

    Passing e as the cause keeps its type, message and stack trace, shown as "Caused by:" in the trace, while the new message adds context.
  4. 4. Where should a single broad catch (Exception e) usually live?

    At a boundary, one broad catch can log the failure and keep the rest of the program running. Deeper code should catch only the specific exceptions it can handle.
  5. 5. Both the body and close() of a try-with-resources block throw. What does the caller receive?

    try-with-resources keeps the primary exception from the body and records the cleanup failure with addSuppressed, so neither is lost.

Summary

  • An empty catch block hides failures; handle deliberately, propagate, or comment why ignoring is safe.
  • Catch specific exception types where you can act on them; use one broad catch only at boundaries.
  • Fail fast: validate inputs with Objects.requireNonNull, IllegalArgumentException and clear messages.
  • Wrap with the original exception as the cause, never just its message.
  • return or throw inside finally discards the real exception; try-with-resources keeps it and records suppressed ones.
  • Use Optional or sealed result types for expected outcomes; reserve exceptions for broken preconditions and failures.
  • Log an exception once, where it's handled, by passing it to the logger.

Next: Debugging Java Programs, where you'll read stack traces, use assertions and track down the most common Java bugs.