Exceptions
The Throwable hierarchy, checked vs unchecked exceptions, try/catch/finally, try-with-resources, custom exceptions, chaining, and best practices for error handling in Java.
Java signals errors by throwing exception objects that unwind the call stack until a matching catch handles them. If nothing catches it, the thread dies and the stack trace is printed.
The hierarchy
| Kind | Examples | Compiler forces handling? | Meaning |
|---|---|---|---|
| Error | OutOfMemoryError, StackOverflowError | No | Serious JVM problems; don't catch |
| Checked exception | IOException, SQLException, InterruptedException | Yes: catch or declare throws | Recoverable conditions outside your control |
| Unchecked (RuntimeException) | NullPointerException, IllegalArgumentException, IllegalStateException | No | Programming errors / violated preconditions |
try / catch / finally
try {
int n = Integer.parseInt(input);
process(n);
} catch (NumberFormatException e) {
log.warn("Bad number: {}", input);
} catch (IOException | TimeoutException e) { // multi-catch
throw new ServiceException("processing failed", e);
} finally {
metrics.increment("processed"); // always runs (success, exception, or return)
}- Catch blocks are checked in order; put specific types before general ones.
finallyruns even if thetryreturns. Areturninsidefinallyoverrides the earlier return and swallows exceptions — never do it.
try-with-resources
Any AutoCloseable declared in the parentheses is closed automatically, in reverse order, even if an exception is thrown:
try (var in = Files.newBufferedReader(path);
var out = Files.newBufferedWriter(target)) {
in.transferTo(out);
} // out.close(), then in.close()If both the body and close() throw, the body's exception propagates and the close exception is attached as suppressed (e.getSuppressed()) instead of being lost.
Throwing and custom exceptions
public class InsufficientFundsException extends RuntimeException {
private final long shortfallCents;
public InsufficientFundsException(long shortfallCents) {
super("Insufficient funds: short by " + shortfallCents + " cents");
this.shortfallCents = shortfallCents;
}
public long shortfallCents() { return shortfallCents; }
}
void withdraw(long cents) {
if (cents <= 0) throw new IllegalArgumentException("amount must be positive: " + cents);
if (cents > balance) throw new InsufficientFundsException(cents - balance);
balance -= cents;
}Prefer standard exceptions where they fit (IllegalArgumentException, IllegalStateException, UnsupportedOperationException, NoSuchElementException); create custom ones for domain errors callers will handle specifically.
Chaining: never lose the cause
try {
repo.save(order);
} catch (SQLException e) {
throw new OrderPersistenceException("Could not save order " + order.id(), e); // pass the cause
}The stack trace then shows "Caused by: java.sql.SQLException…", which is often the most important line.
The checked exceptions debate
- The compiler ensures callers consider failure
- The signature documents what can go wrong
- Boilerplate: catch-and-rethrow everywhere
- Leaks implementation details (
SQLExceptionfrom a repository interface) - Don't work with lambdas (
Functioncan't throw checked exceptions) - Most modern JVM frameworks (Spring) and languages (Kotlin, C#) use unchecked exceptions
A common modern style: use unchecked exceptions for most errors, wrap checked exceptions from libraries at the boundary (UncheckedIOException), and use checked ones only where a caller can and should recover.
Best practices
- Fail fast: validate arguments at the start of a method (
Objects.requireNonNull(x, "x")). - Catch what you can handle, where you can handle it. Let others propagate.
- Don't use exceptions for control flow: creating stack traces is expensive, and the logic is hard to follow. Check
map.containsKeyrather than catching a failure. - Log or rethrow, not both — otherwise the same error appears many times in logs.
- Include context in messages: IDs and values, not "error occurred".
- Restore the interrupt flag if you catch
InterruptedExceptionand can't rethrow:Thread.currentThread().interrupt(); - Don't catch
ThrowableorErrorexcept at the very top level (to log before dying). - In APIs, translate exceptions into proper responses at one central place (e.g. Spring's
@ControllerAdvice).
Optional instead of null
For "might not have a value" results, return Optional<T> rather than null or throwing:
Optional<User> findByEmail(String email);
String name = repo.findByEmail(e)
.map(User::name)
.orElse("anonymous");
User u = repo.findByEmail(e).orElseThrow(() -> new NotFoundException(e));Use Optional for return values only — not for fields or parameters.
- Throwable → Error (don't catch) and Exception; RuntimeException subclasses are unchecked.
- Checked exceptions must be caught or declared; many modern codebases favour unchecked.
- try-with-resources closes AutoCloseables safely and records suppressed exceptions.
- Always chain causes; never swallow exceptions; log once with context.
- Use Optional for absent results instead of null.
QChecked vs unchecked exceptions?easy
Checked exceptions (subclasses of Exception but not RuntimeException) must be caught or declared with throws; they represent recoverable conditions such as I/O failure. Unchecked exceptions (RuntimeException and its subclasses) need no declaration; they usually indicate programming errors like null dereferences or invalid arguments. Errors are also unchecked and indicate serious JVM problems.
QDoes finally always execute?medium
Almost always — after normal completion, after an exception, and even after a return in try or catch. It does not run if the JVM exits (System.exit), the process is killed, or the thread runs forever or deadlocks inside try. A return in finally overrides other returns and discards exceptions, so avoid it.