Java Programming
Java Exceptions: Checked vs Unchecked, try-with-resources and Good Error Design
Beginner8 min readUpdated
Exceptions are how a Java method reports that it could not do what it promised. This guide explains the hierarchy and propagation rules, when to use checked versus unchecked exceptions, how try-with-resources closes resources correctly, how to design your own exception types and how to log and translate errors without losing the cause. You will be able to write error handling that fails loudly, cleanly and once.
What you will learn
- Explain the Throwable hierarchy and how an exception propagates up the call stack
- Choose between checked and unchecked exceptions for a given failure
- Use try-with-resources and multi-catch correctly, including suppressed exceptions
- Design custom exceptions that carry context and preserve the cause
- Avoid the classic anti-patterns: swallowing, catching Throwable, exceptions for control flow
An exception is a signal that a method could not fulfil its contract, carried up the call stack until something handles it. Java's design has two distinctive traits: exceptions are ordinary objects with a class hierarchy, and the compiler enforces handling for one branch of that hierarchy. Both are simple to state and easy to misuse, and misuse has real costs: swallowed errors that surface as corrupted data weeks later, stack traces that point at the wrong place, resources leaked on every failure. This guide covers the mechanics, the design choices and the patterns that hold up in production. Code targets Java 21.
The hierarchy and what each branch means
Throwable
├── Error JVM-level failures: OutOfMemoryError, StackOverflowError, LinkageError
└── Exception
├── RuntimeException unchecked: NullPointerException, IllegalArgumentException,
│ IllegalStateException, IndexOutOfBoundsException, ArithmeticException
└── (everything else) checked: IOException, SQLException, InterruptedException, ParseException
Errors signal conditions an application should not try to recover from. Catching OutOfMemoryError and carrying on is rarely meaningful, because the JVM may already be in an inconsistent state.
Checked exceptions extend Exception but not RuntimeException. A method that can throw one must declare it with throws, and a caller must either catch it or declare it too. The compiler enforces this, which is the whole point: the failure is part of the method's signature, and callers cannot ignore it by accident.
Unchecked exceptions extend RuntimeException. They can be thrown anywhere without declaration, and they conventionally represent programming errors: a null where an object was required, an argument out of range, a method called in the wrong state. The caller is not expected to catch them; the fix is to correct the bug.
Throwable itself carries a message, a cause, a stack trace captured at construction, and a list of suppressed exceptions. The stack trace capture is what makes exceptions expensive relative to a return value — walking the stack costs microseconds, not nanoseconds — and it is why exceptions should mark exceptional situations rather than expected outcomes.
Propagation: try, catch, finally
When a statement throws, execution abandons the rest of the block and the JVM searches the enclosing try statements, innermost first, for a catch whose type matches. If none matches in the current method, the method exits abruptly and the search continues in the caller. An exception that reaches the top of a thread with no handler terminates that thread, after the thread's uncaught-exception handler has printed the trace; when it was the last non-daemon thread, the JVM exits.
static int parsePort(String raw) {
try {
int port = Integer.parseInt(raw);
if (port < 1 || port > 65_535) {
throw new IllegalArgumentException("port out of range: " + port);
}
return port;
} catch (NumberFormatException e) {
throw new IllegalArgumentException("port is not a number: " + raw, e); // translate, keep cause
} finally {
System.out.println("parsePort finished"); // runs either way
}
}
Catch clauses are tried in order, and a clause for a supertype placed before one for a subtype is a compile error because the second could never run. Multi-catch (catch (IOException | SQLException e)) handles several unrelated types with one block; the variable is implicitly final.
finally runs whether the try block completes, returns or throws. Its purpose is cleanup that must happen regardless. Two rules keep it safe: never return from a finally (it silently discards any pending exception), and never let finally throw (a throw there replaces the original exception, hiding the actual failure).
try-with-resources
Before Java 7, closing a stream correctly took a nested try/finally with null checks, and even careful code lost the original exception if close() also failed. try-with-resources handles all of it: any object implementing AutoCloseable declared in the parentheses is closed automatically, in reverse order of declaration, after the block.
Path source = Path.of("input.csv");
Path target = Path.of("output.csv");
try (BufferedReader in = Files.newBufferedReader(source);
BufferedWriter out = Files.newBufferedWriter(target)) {
String line;
while ((line = in.readLine()) != null) {
out.write(line.toUpperCase());
out.newLine();
}
} catch (IOException e) {
throw new UncheckedIOException("Failed to copy " + source + " to " + target, e);
}
If the block throws and close() throws too, the block's exception propagates and the close failure is attached to it via addSuppressed; you can inspect it with getSuppressed(). Java 9 allowed an effectively final variable declared earlier to be used directly: try (existingConnection) { ... }.
Implement AutoCloseable on your own classes that hold a resource — a connection, a lock, a temporary directory — and document whether close() is idempotent. Closeable is the I/O-specific subinterface whose close() throws IOException and must be idempotent.
Choosing checked or unchecked
This is the design decision that divides Java developers. The language authors' guideline is clear: checked exceptions for conditions a caller can reasonably be expected to recover from, unchecked for programming errors. In practice, three forces push modern code towards unchecked:
- Lambdas and streams. Functional interfaces such as
FunctionandSupplierdo not declare checked exceptions, so a checked exception inside a lambda must be caught and wrapped right there. The streams guide shows how noisy that becomes. - Layering. A
SQLExceptionfrom the persistence layer means nothing to a web controller. Each layer would have to declare or wrap it, so the signature pollution spreads across the whole application. - Frameworks. Spring's
DataAccessExceptionhierarchy, JPA'sPersistenceExceptionand most HTTP clients are unchecked, and Kotlin — which runs on the same JVM — dropped checked exceptions entirely.
A workable policy: keep checked exceptions at the edges where a specific recovery exists (FileNotFoundException when the user chose the file, InterruptedException in concurrent code), and translate everything else into unchecked exceptions with a descriptive type as soon as it crosses into your code. UncheckedIOException exists in the JDK for exactly this translation.
| Situation | Use |
|---|---|
| Caller passed a bad argument | IllegalArgumentException (or NullPointerException via Objects.requireNonNull) |
| Object is in the wrong state for the call | IllegalStateException |
| Operation not supported by this implementation | UnsupportedOperationException |
| External resource failed and a retry or alternative is plausible | Checked, or a domain-specific unchecked type at the boundary |
| Business rule violated (insufficient funds) | Domain exception, usually unchecked, or a result type |
| Bug detected internally | AssertionError or IllegalStateException |
Designing your own exceptions
A custom exception earns its existence when callers need to catch it separately or when it carries context a generic type cannot. Keep the class small, extend the right base, and provide the standard constructors so a cause can always be attached:
public class PaymentDeclinedException extends RuntimeException {
private final String paymentId;
private final String declineCode;
public PaymentDeclinedException(String paymentId, String declineCode, Throwable cause) {
super("Payment %s declined with code %s".formatted(paymentId, declineCode), cause);
this.paymentId = paymentId;
this.declineCode = declineCode;
}
public String paymentId() { return paymentId; }
public String declineCode() { return declineCode; }
}
Fields let a handler act on structured data — map a decline code to an HTTP status, decide whether to retry — without parsing the message. A hierarchy helps when handlers want different granularity: PaymentException as a base, PaymentDeclinedException and PaymentGatewayUnavailableException as leaves; a caller can catch the base or a leaf.
Name exceptions with the Exception suffix and describe the problem, not the layer ("OrderNotFoundException", not "RepositoryException"). Make the message useful to a person reading a log at 3 a.m.: include identifiers and values, never sensitive data such as passwords or full card numbers.
Chaining and translation
When you catch a low-level exception and throw a higher-level one, pass the original as the cause. The stack trace then prints Caused by: sections all the way down, which is often the only way to find the actual failure. Throwing a new exception without the cause is the single most damaging thing you can do to future debugging.
Translation should happen once, at the layer boundary. If every method rewraps, the trace becomes a five-deep onion of identical messages.
Handling: where and how
Good handling follows a rule of thumb: catch late, throw early. Throw as soon as you detect the problem (validate arguments at the top of a method) and catch only where you can do something meaningful. The meaningful options are:
- Recover — retry, use a default, fall back to a cache.
- Translate — wrap into a type the current layer's callers understand, with the cause.
- Report and stop — at a boundary (HTTP handler, message listener,
main), log with the full trace and convert to a response or exit code.
Everything else — logging and rethrowing, catching and returning null, empty catch blocks — makes things worse. Logging and rethrowing produces the same trace twice, once at each layer; log at the boundary only.
// Boundary handler: the one place that catches broadly
public HttpResponse handle(HttpRequest request) {
try {
return service.process(request);
} catch (PaymentDeclinedException e) {
return HttpResponse.status(402).body(e.declineCode()); // expected domain outcome
} catch (RuntimeException e) {
log.error("Unhandled failure for request {}", request.id(), e); // full trace, once
return HttpResponse.status(500).body("internal error");
}
}
Pass the exception object as the last argument to the logger, not e.getMessage() — the logging frameworks print the full trace only when they receive the Throwable.
InterruptedException
InterruptedException deserves its own rule. It is thrown by blocking methods (sleep, join, BlockingQueue.take) when another thread asks this one to stop. Swallowing it cancels that request. If you cannot propagate it, restore the flag: Thread.currentThread().interrupt(); and then exit the work as quickly as possible. The concurrency guide covers the protocol.
Exceptions and performance
Constructing an exception fills in the stack trace, which walks every frame of the current thread. In a deep call stack that is tens of microseconds — negligible for a genuine failure, ruinous in a loop that throws to signal "not found". Options when an exception genuinely must be cheap (a library's internal control signal, for instance) are to reuse a pre-allocated instance or override fillInStackTrace to return this; both trade debuggability for speed and belong in library code, not in application logic.
The JIT compiler also optimises a hot method that throws repeatedly by dropping the stack trace after a while (-XX:-OmitStackTraceInFastThrow disables this), which is why a production log can suddenly show NullPointerException with no trace at all. If you see that, the exception has been thrown thousands of times already.
Common mistakes
Empty catch blocks. catch (Exception e) {} turns a failure into silent data corruption. If the exception is genuinely ignorable, say why in a comment and log at debug level.
Catching Throwable or Error. You will catch OutOfMemoryError and StackOverflowError and continue with a JVM that may be in an inconsistent state. Catch Exception at boundaries at most.
Losing the cause. throw new ServiceException("failed") inside a catch, without e. The real reason is gone.
Returning from finally. It overrides both the return value and any in-flight exception.
Exceptions as return codes. Throwing UserNotFoundException from a lookup that is expected to miss half the time. Return Optional<User> instead.
Overly broad throws Exception. It tells callers nothing and forces them into equally broad catches. Declare specific types or use unchecked exceptions.
Logging at every layer. One failure, six stack traces in the log, and someone paging through them at midnight.
Validating too late. A null argument stored in a field and dereferenced three calls later produces a trace pointing far from the bug. Objects.requireNonNull(x, "x") at the top of the method points at the culprit.
Key takeaways
- Checked exceptions are part of a method's signature and force callers to decide; unchecked ones signal bugs or failures the caller cannot fix. Modern code leans unchecked, translating at layer boundaries.
- try-with-resources closes
AutoCloseableresources in reverse order and preserves the original exception, attachingclose()failures as suppressed. - Never return from or throw inside
finally; it hides the exception that mattered. - Always pass the original exception as the cause when translating, and translate once per layer, not at every call.
- Catch late, at a boundary that can recover, translate or report; log the full
Throwablethere and nowhere else. - Exceptions capture a stack trace on construction; use return values or
Optionalfor expected outcomes.
Sources and further reading
Frequently asked questions
- Should I use checked or unchecked exceptions?
- Use a checked exception when the caller can realistically recover and you want the compiler to force a decision — a missing file the user can re-select, a timeout worth retrying. Use an unchecked exception for programming errors and for failures nothing at the call site can fix. Most modern libraries and frameworks lean unchecked because checked exceptions do not compose with lambdas and generic code.
- What happens if both the try block and the finally block throw?
- The exception from finally replaces the one from try, which is lost. That is why finally blocks should not contain code that can throw. try-with-resources fixes this for resources: the original exception wins and any close() failure is attached to it as a suppressed exception.
- Is it bad to catch Exception?
- At a boundary — a request handler, a thread's run method, a scheduled task — catching Exception to log and convert to a response is correct, because letting it escape would kill the thread or produce a stack trace to the user. Deep inside business code it hides bugs; catch the specific types you can handle and let the rest propagate.
- Why should I not use exceptions for control flow?
- Creating an exception captures the stack trace, which costs far more than a boolean check, and it makes code harder to read because the normal path is hidden in a catch. Use a return value, Optional or a validation check for expected conditions, and reserve exceptions for situations the method could not handle.