Lesson · Exception Handling
Exception traps and best practices
15 min readTraps & Best Practices
Empty catches, omni-catches, exceptions as control flow, dropped causes and catching Throwable: five traps that all look reasonable in review. Recognition is the whole skill.
The bug that hid for a week
A save method failed silently for days and nobody noticed, because somebody once made it impossible to notice:
try { repository.save(order); } catch (Exception e) { // TODO: handle this }
Predict: what was lost when that catch ran? The failure itself, its type and message, its stack trace, and the evidence that orders were not being saved. An empty catch is not error handling; it is error deletion, and it steals the debugging session of whoever comes next.
The rules that follow from one question
Every best practice below is the same question asked at a different layer: who can do something useful about this?
- Catch only what you handle: a catch block should change the outcome (substitute, retry, translate, report). Anything else belongs in a caller's signature, not in a silent clause.
- Never catch to forget: an empty or log-only catch that continues as if nothing happened converts a detected failure into an undetected one.
- Translate with the cause, or do not translate: wrapping adds domain vocabulary; dropping the cause deletes the evidence. The two travel together.
- Do not use exceptions for control flow: expected outcomes (absent, invalid input, out of range) get checks and return values; exceptions are for the exceptional.
- Never catch `Throwable` or `Error` to keep going: those are conditions under which the program cannot promise sane operation.
- Keep `finally` free of return and throw: both silently replace whatever the try was doing (verified in the basics and advanced lessons).
Logging is not handling. A stack trace in a log at the wrong layer often means the same failure will also be logged (or dropped) again later; decide the single layer that owns the failure.
Name the trap yourself
Five catch blocks, all of which have appeared in production somewhere. Pick the verdict for each:
- If the block erases the failure, that is the swallow.
- If the block pretends to handle everything, that is the omni-catch: too broad to be true.
- If a check would have done, it is flow control wearing an exception costume.
- If the failure gains vocabulary while the cause rides along, that is translation at work.
- If it reaches for
Throwable, nothing it does next can be trusted.
The five verdicts cover the five traps. Empty swallow, omni-catch, flow control, dropped-cause translation, and Throwable: recognise those five and most real-world exception bugs become pattern matches.
Policy lab · name the trap
pick a catch block, then a verdictWhich trap is it?
Choose a verdict above; the mechanism will explain itself.
The mechanisms behind every verdict were executed in the previous lessons of this chapter: swallowed emptiness, broad catches, flow control, cause-chained translation and the Throwable rule.
The exception-hygiene playbook
Reviewing or writing handling code, in order:
- For every catch block, say out loud what the program does differently because of it; if the answer is 'nothing', delete the catch or fix the layer.
- Narrow the caught type until it names the failure being handled;
Exceptionappears only at deliberate boundaries. - When translating, chain the cause (
new X(msg, e)) and choose the road consciously (checked vs unchecked). - Replace expected-outcome exceptions with checks or return values (the label-search loop is a binary search, not a tripped wire).
- Ban
catch (Throwable),return-in-finally and empty catches in review checklists; they are mechanically detectable.
Handling is a decision, and decisions leave traces: a narrower type, a translated cause, a changed outcome. A catch block that leaves no trace of any of the three was never handling anything.
Five traps, one question: who can act on this failure?
Empty catches erase evidence, omni-catches pretend to handle what they cannot, exceptions-as-control-flow turn logic into accidents, translations without causes delete the root story, and catches of Throwable gamble on a JVM that already said no. Every rule resolves to asking which layer can do something useful, and letting every other layer see the failure.
Interview angles
Why is an empty catch block so harmful, and what replaces it?+
It converts a detected failure into an undetected one: the operation did not happen, and nothing records that. If truly no action is possible, the honest options are letting it propagate or logging once with context at a deliberate boundary.
The harm is asymmetric: the empty catch costs one comment to write and days to debug later. Reviewers flag it mechanically, and linters can too; the pattern has no legitimate form.
catch (Exception e) { } // evidence deleted catch (IOException e) { rebuildIndex(); } // evidence used: handling catch (IOException e) { throw new Wrap("save order " + id, e); } // evidence translated
Common misconception: That catching-without-handling is 'defensive'. It defends nobody: the failure already happened; the block only hides it.
Follow-up: Which single log line would have shortened the bug hunt the most?
What is wrong with catching Exception in the middle of logic?+
It claims to handle everything from checked IO to NullPointerException: bugs and expected failures in one bucket, usually logged and stepped over, which converts programming errors into data corruption.
At boundaries (request handlers, task runners) a broad catch is honest: nothing should escape there. Inside logic, the catch should name the failures the code can genuinely answer, so unexpected ones keep travelling.
// boundary: honest try { handle(request); } catch (Exception e) { respond500(e); } // middle: too broad try { parseRow(line); } catch (Exception e) { log(e); } // NPEs vanish too
Common misconception: That catch-all plus logging is safe. Logging preserves evidence; the swallowed control flow still corrupts state.
Follow-up: Which exception types in that middle catch should never have been caught there?
When are exceptions being used as control flow, and why is it bad?+
When ordinary, expected outcomes travel as throws: index lookups caught as misses, parse failures as validation, end-of-stream as a signal. It is bad because it makes the normal path exceptional: slower, harder to read, and prone to masking real failures.
The tell is a catch block whose condition mirrors a trivial check. contains before get, a length test before indexing, Optional or null-return instead of caught misses: the check expresses the expectation the caller actually has.
try { return list.get(i); } catch (IndexOutOfBoundsException e) { return -1; } // flow control return i >= 0 && i < list.size() ? list.get(i) : -1; // the check
Common misconception: That control flow via exceptions is just 'clever'. It works, at the price of performance (each construction records a trace) and of every reader's expectations.
Follow-up: Which JDK APIs were redesigned to avoid exactly this pattern?
How do you translate an exception correctly?+
Wrap it in the higher-level type with a message that adds context and the original passed as the cause: throw new OrderException("save order " + id, e). Never construct the wrapper without e.
Translation is the boundary's job: callers see domain failures, diagnostics keep the chain. Losing the cause is the common half-measure: the wrapper appears, the story disappears, and the root cause must be reproduced from scratch.
catch (SQLException e) { throw new OrderException("save order " + id, e); // cause rides along }
Common misconception: That wrapping is optional if the message is detailed. The message describes this layer; only the cause preserves the layer below.
Follow-up: What does the report look like when two translations nest?
Why is catch (Throwable) never right for continuing?+
Throwable includes Errors: out-of-memory, stack overflow, missing linkage. After catching one, the program has no promise of sane execution; retrying or continuing on that footing is guesswork dressed as resilience.
The one legitimate shape is a top-level handler that records the failure and exits deliberately, or rethrows. Frameworks may catch Throwable at thread boundaries solely to report and terminate the thread.
catch (Throwable t) { retry(); } // guesswork catch (Throwable t) { log.fatal(t); throw t; } // report and stop: legitimate
Common misconception: That catching Throwable is 'the most protective'. Protection comes from isolation at boundaries, not from swallowing the JVM's own alarms.
Follow-up: What does a retry loop under an OutOfMemoryError actually promise?