Java exceptions: checked vs unchecked, try-catch-finally and the call stack
A failure must tell the caller what it can do: fix the input, retry, or stop. The Throwable hierarchy, checked vs unchecked, try-catch-finally, try-with-resources, propagation through the call stack, the cost of stack traces, and how to review AI-written error handling.
On this page
1. The problem
The payment gateway times out after 3 seconds. pay() has catch (Exception e) { log.error(...); return null; }, and the controller returns 200 with an empty body. In one peak hour, 1,200 orders sit at "processing" forever, and nobody knows whether to retry or tell the customer.
2. Key idea
The place that detects an error rarely knows what to do; it carries enough information for the boundary layer (controller, consumer, job) to decide.
| Error kind | What the caller can do | Java | The boundary returns |
|---|---|---|---|
| Bad input, business rule broken | fix and resend | IllegalArgumentException, a business exception |
400, 409 with a reason |
| Transient (timeout, lost connection) | retry later | SocketTimeoutException wrapped in your own exception |
bounded retry, or 503 |
| Bug, broken environment | nothing, just stop | NullPointerException, OutOfMemoryError |
500, log the full stack trace |
2.1 Checked or unchecked?
Throwable splits into Error (the JVM is in trouble, don't catch) and Exception. Checked means an Exception outside RuntimeException: the compiler forces catch or throws; the JVM doesn't care.
| Approach | Use when | Don't use when |
|---|---|---|
| Unchecked business exception | a rule is broken and the caller needs a code and data | "nothing found" is a normal result |
Optional |
"not found" is a valid result | the caller must not ignore the error |
| Checked exception | narrow API, nearby caller that can really recover | the error must pass through lambdas, streams, many layers |
catch (Exception e) |
the outermost handler: @RestControllerAdvice, a consumer loop |
in business code |
A return inside finally swallows the exception from try. Open resources (Connection, streams) with try-with-resources: they close themselves, and errors while closing are kept as suppressed.
3. In Java
Throw the kind of error that says what the caller can do, and keep the cause when wrapping.
Receipt pay(Gateway gateway, Order order) {
if (order.amount() <= 0) // bad input: message includes the value
throw new IllegalArgumentException("amount must be positive, got " + order.amount());
try {
return gateway.charge(order); // throws IOException (checked)
} catch (SocketTimeoutException e) { // subclass of IOException: goes first
throw new PaymentUnavailableException("gateway timeout for order " + order.id(), e);
} catch (IOException e) { // can't recover here
throw new IllegalStateException("gateway protocol error for order " + order.id(), e);
}
}
// timeout -> PaymentUnavailableException, cause=java.net.SocketTimeoutException: Read timed outOther languages: Go's fmt.Errorf("charge %s: %w", id, err) keeps the cause; Node.js has new Error(msg, { cause }).
The cost of exceptions, and NPEs without stack traces
- The expensive part of an exception is capturing the stack trace at creation, not the
throw. Don't use exceptions for normal control flow (checking whether an email exists). - Helpful NullPointerExceptions (Java 14+) name the null variable:
Cannot invoke "Order.id()" because "order" is null. - HotSpot enables
-XX:+OmitStackTraceInFastThrowby default: when the same NPE is thrown repeatedly in JIT-compiled code, the JVM reuses one instance without a stack trace. Production logs have fullatlines at first and only a barejava.lang.NullPointerExceptionhours later. - When catching
InterruptedException, callThread.currentThread().interrupt()or rethrow; swallowing it means the thread can't be stopped.
4. Working with AI
AI tends to handle errors "to be safe": catch Exception, return null, retry everything; happy-path tests still pass.
Hand to AI: listing the exceptions a method can throw, an assertThrows test per branch, summarising long stack traces.
Check in AI-written code:
- No
catch (Exception e)outside the outermost handler; nocatchthat returnsnull. - Every wrapped exception passes the
cause. - Retries only for transient errors, bounded, on idempotent operations.
- Resources are opened with try-with-resources; no
returninsidefinally. - Tests check both the exception type and that state is unchanged (balance, data).
5. Exercises
Exercise 1: Review a retry function
The AI says: "fault tolerant, retries 3 times". Find the bugs, name a test that proves them, fix it.
Receipt payWithRetry(Gateway gateway, Order order) {
for (int i = 0; i < 3; i++) {
try {
return gateway.charge(order);
} catch (Exception e) {
log.warn("retry {}", i);
}
}
throw new PaymentUnavailableException("gateway down");
}Solution to Exercise 1
- Retries every exception: a declined card still hits the gateway 3 times, and an NPE from a bug is "retried" too. Test: a fake gateway that always throws
CardDeclinedException; assert one call and aCardDeclinedException. The current code calls 3 times and reports "gateway down". - Loses the cause: the final exception doesn't carry the original error.
- Retries a charge without an idempotency key: a timeout doesn't mean nothing was charged; a retry may charge twice.
Fix: catch only PaymentUnavailableException (transient), back off between attempts, send the same idempotency key on every attempt, and rethrow with the last error as the cause.
Exercise 2: Read a missing-stack-trace incident
After 6 hours the service logs only bare java.lang.NullPointerException lines, no at lines, about 40,000 per minute. Right after startup there were full stack traces. Diagnose it, say what you do in the first 15 minutes, and fix the root cause.
Solution to Exercise 2
- Diagnosis:
OmitStackTraceInFastThrow: a repeated NPE in JIT-compiled code reuses an instance without a stack trace. - 15 minutes: search the logs for the first occurrences after the latest startup; they still have the full trace and the null variable name. If logs have rotated away, restart one instance with
-XX:-OmitStackTraceInFastThrow. - Root fix: stop nulls at the boundary (validate input,
Objects.requireNonNullin constructors); alert on error rate. No need to disable the flag permanently.
Summary
- Three error groups: bad input, transient, bug; the caller handles each differently.
- Checked exceptions must be caught or declared; catch subclasses before superclasses.
- Catch where a decision is made; keep the
causewhen wrapping; never swallow errors. - Try-with-resources for resources; no
returninsidefinally. - Retry only transient errors, bounded, on idempotent operations.
Read more: Part 2: Custom exceptions and error handling in Spring Boot.
Practice interview questions on this topic
- What is the difference between final, finally and finalize? Does finally always run?
- What is the difference between checked and unchecked exceptions? Which class should a custom exception extend?
- What problem does try-with-resources solve? What is a suppressed exception?
- Are exceptions expensive in Java? How do you optimize them?
- Where does an exception go when it is thrown in an executor thread or an @Async method?
Comments
Community rules