Lesson · Exception Handling
Checked vs unchecked: two roads out of a method
16 min readChecked vs Unchecked
Checked exceptions turn handling into a compile-time obligation: catch or declare. Unchecked ones mark programming errors the compiler leaves alone. The road choice is a design decision, and lambdas sharpen its friction.
The compiler that refuses to let it slide
Reading a file without mentioning the possibility of failure does not compile, and the message explains the obligation:
void load(String path) { new FileReader(path); // error: unreported exception FileNotFoundException; } // must be caught or declared to be thrown // the two legal answers: void load(String path) throws IOException { ... } // declare void load2(String path) { try { ... } catch (IOException e) { ... } } // handle
Predict: what is the compiler actually demanding? A decision, recorded in code: either this method handles the failure, or its signature admits the failure to every caller. Checked exceptions make 'somebody must think about this' a compile-time fact.
The two roads
The hierarchy from last lesson, read as policy:
| Checked (direct Exception children) | Unchecked (RuntimeException family) | |
|---|---|---|
| Compiler | Forces handle-or-declare | No obligation; they travel silently |
| Typical examples | IOException, SQLException, ParseException, ClassNotFoundException | NullPointerException, IllegalArgumentException, IllegalStateException, IndexOutOfBoundsException |
| Meaning | A condition the caller can act on | A bug: broken precondition, null, wrong state |
| Who fixes it | The code, at some layer, deliberately | The developer, upstream of the throw |
The dividing question is agency. Could a caller, given the information, do something useful (retry, substitute, report)? That is a checked candidate. Could only a code change have prevented it? That is unchecked.
Choosing a road as a designer
Three positions worth holding at once:
- Checked for recoverable, expected failures: file and network I/O, parsing user input, database calls. The obligation in the signature is the documentation.
- Unchecked for programming errors:
IllegalArgumentExceptionon a bad parameter,IllegalStateExceptionon wrong call order,NullPointerExceptionwhere a value was required. Nobody can 'handle' a bug; the fix is upstream. - The honest controversy: checked exceptions create ceremony (deep
throwslists, versioning pain when a new failure appears) and famously clash with lambdas; some designers use them sparingly for that reason. The lesson is not to pick a side but to choose consciously and consistently.
Translation is the pressure valve. A layer that must hide a checked failure from its callers wraps it (throw new IllegalStateException("config unreadable", e)), keeping the cause; the advanced lesson assembles the full pattern.
Where the friction shows: lambdas and method references
Standard functional interfaces (Runnable, Function, Consumer) declare no checked exceptions, so a checked-throwing call inside a lambda has nowhere to travel:
values.forEach(n -> risky(n)); // error: unreported exception IOException values.forEach(n -> { // the workaround: handle inside try { risky(n); } catch (IOException e) { report(e); } });
- The lambda body must satisfy
Consumer.accept, whose signature says nothing about checked exceptions. - So the checked road ends at the lambda's braces: handle there, or define your own functional interface that declares
throws IOException. - Method references hit the same wall when the method declares checked exceptions.
- This is the biggest practical cost of checked exceptions, and it is a compile-time cost: the compiler is doing exactly what the road promised.
Verified in this lesson's demo: the direct forEach(n -> risky(n)) form is refused with unreported exception IOException; must be caught or declared to be thrown, and the wrapped form runs and reports each failure.
Two roads · compiler obligation decides the policy
pick a typechecked road · handle or declare
unchecked road · fix upstream
The compiler
Must be caught or declared in the signature
Who acts
The layer that can retry, substitute or report (or the caller, via throws)
Usually raised by
Files, sockets, streams: the outside world
The canonical checked exception: the signature documents that the operation faces I/O.
Lambda friction verified in this lesson: a checked call inside a standard functional interface is refused until handled at the braces.
The two-roads playbook
Placing failures on a road, in order:
- Ask the agency question: can a caller act on this failure with information at hand? Checked candidate; otherwise unchecked.
- For the checked road, declare in the signature until a layer exists that can genuinely handle it; do not catch early just to silence the compiler.
- For the unchecked road, enforce preconditions (
Objects.requireNonNull, range checks) so the bug stops at its source with a precise message. - At boundaries that must not leak implementation types, translate: wrap with context and the original cause attached.
- Inside lambdas, expect the checked road to end at the braces; handle there or define a functional interface that declares the thrown type.
The road is a promise about who thinks next. Checked hands the thought to the caller by contract; unchecked keeps it with the developer. Choose the promise, and the signatures stay honest.
Checked means the compiler insists; unchecked means the developer should have known
Checked exceptions (direct Exception children) force handle-or-declare and suit recoverable, caller-actionable conditions. Unchecked ones (RuntimeException family) mark bugs and travel silently until they explode with a message that names the broken invariant. Translation with the cause preserved is the standard boundary move, and lambdas are the place the checked road visibly ends.
Interview angles
What makes an exception checked?+
Its position in the hierarchy: a direct descendant of Exception (not RuntimeException, not Error). The compiler then forces every caller to catch it or declare it.
The obligation composes up the call stack: every method that lets a checked exception travel must say so. That is why deep libraries isolate checked failures at their boundaries ('translation') instead of sprinkling throws clauses.
void load() throws IOException { ... } // the signature carries the obligation
Common misconception: That checked means 'important'. Importance has nothing to do with it; position in the tree does.
Follow-up: Where does the compiler stop enforcing a checked exception's journey?
When is a checked exception the right tool?+
When the failure is an expected, recoverable condition of the operation and the caller has enough information to act: retry, substitute, report, or choose a different input.
I/O, parsing untrusted input, and database calls are the canonical cases. The signature becomes documentation: callers read throws IOException and know the operation faces the outside world.
String content = Files.readString(path); // the compiler mentions the sky falling
Common misconception: That recoverable means 'the program continues'. It means the decision is knowable at compile time by a caller who can respond to it.
Follow-up: What does recoverable look like when nobody upstream can actually recover?
What are the strongest criticisms of checked exceptions?+
Ceremony and versioning: throws clauses propagate through stacks, adding a failure type later breaks every caller, and lambdas (with their exception-free functional interfaces) turn the obligation into wrapping noise.
The friction is real and documented in the ecosystem's shift toward unchecked domain exceptions in newer libraries. The balanced response is deliberate use: checked at true public edges where the caller can decide, unchecked for everything internal and bug-like.
// the famous wall: Consumer.accept cannot throw checked exceptions list.forEach(x -> read(x)); // requires try/catch inside the lambda
Common misconception: That the criticism means 'never use checked'. It means the cost is real, so pay it where the benefit (forced caller attention) outweighs the ceremony.
Follow-up: Which two strategies hide checked failures without losing information?
How do checked exceptions interact with lambdas, exactly?+
Functional interfaces like Runnable, Function and Consumer declare no exceptions, so the lambda body cannot let a checked exception escape: handle it inside, or define a custom interface that declares the throws.
The compiler message is the familiar 'unreported exception ... must be caught or declared'. Verified in the demo: the direct form is refused and the try-inside form runs. Method references that throw checked exceptions hit the same wall.
interface IoTask { void run() throws IOException; } // custom: allows the road
Common misconception: That wrapping every lambda in try/catch is the only way. A small custom functional interface (IoFunction, IoConsumer) is often cleaner.
Follow-up: Why can a custom functional interface restore the checked road inside stream code?
What is the modern consensus on which to use?+
There is no single verdict; the defensible position is deliberate use. Checked at boundaries where callers genuinely decide, unchecked for programming errors and most internal failures, and translation to cross layers without losing causes.
Modern Java leans unchecked for domain errors and reserves checked for external, recoverable operations, but plenty of respected APIs differ. Consistency within a codebase matters more than winning the argument.
throw new IllegalStateException("incomplete", e); // translation, cause kept
Common misconception: That one road is simply correct. The reply that ages best in an interview names the trade-off and states a policy.
Follow-up: What does your team's policy say, and where is it written?