Exceptions and Resource Management
Separate happy-path code from failure handling, preserve causes, and close resources safely with try-with-resources.
Why it matters
Start from the concept, not the syntax
Meet a concrete situation where this idea earns its place, then state the boundary it guards.
Things go wrong: files are missing, input is malformed, networks fail. Exceptions separate the happy path from failure handling so each stays readable—and knowing checked versus unchecked tells you when the compiler forces you to care.
By the end of this chapter
Swallowing exceptions or catching Exception hides real failures, so bugs resurface later as mystery behavior somewhere else.
- Checked vs unchecked
- try-with-resources
- Catch order
Mechanism
How Java expresses the concept
Walk the actual types, rules, and runtime behavior involved—the same behavior described in the Java Language Specification.
The mental model
All throwables derive from `Throwable`, which splits into `Error` (serious JVM problems you do not catch) and `Exception`. `RuntimeException` and its subclasses are unchecked, meaning the compiler does not force you to handle them; everything else under `Exception` is checked and must be caught or declared.
Use `try/catch/finally` to recover. `finally` runs whether or not an exception was thrown, which makes it the right place to release resources. Prefer `try-with-resources` for anything implementing `AutoCloseable`; it closes correctly even when an exception occurs.
Throw the most specific exception that fits, and include a message that names the bad value. Catch the most specific type first; a broad `catch (Exception)` hides bugs and can swallow `InterruptedException`.
Checked exceptions are a compiler-enforced handling policy; unchecked exceptions are not required to be caught or declared. That distinction does not determine whether a failure is recoverable or whether it is a programming error. Use domain context to choose the boundary and do not use exceptions for ordinary control flow.
Concept map
Inspect the building blocks as a whole
Use the map as a structural reference; it shows the pieces and their relationships, not an execution sequence.
Core Java
Exceptions and error handling
Exceptions separate happy-path logic from failure handling. Know the hierarchy and the difference between checked and unchecked.
- 01Throwable hierarchy
- 02Checked vs unchecked
- 03try / catch / finally
- 04try-with-resources
- 05Throw specific types
- 06Catch narrow first
Implementation
Encode the smallest runnable example
Write and run the code, then observe the behavior you just predicted with a real Java program.
Runnable snippet path
Predict, run, and change each example
try-with-resources
The reader closes automatically, even if readLine throws.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class Read {
static String firstLine(Path p) throws IOException {
try (var lines = Files.lines(p)) {
return lines.findFirst().orElse("");
}
}
}Remember
Any AutoCloseable works in try-with-resources; closing is guaranteed on every path.
Change one input, predict the result, then compile or test it before continuing.
Custom exception
Extend RuntimeException for a domain error that callers did not have to declare.
class InsufficientFunds extends RuntimeException {
InsufficientFunds(int have, int want) {
super("have " + have + " but want " + want);
}
}Remember
Include the offending values in the message so failures are debuggable.
Change one input, predict the result, then compile or test it before continuing.
Watch out
Break it on purpose, then repair the right layer
Predict the symptom before running the failure case, and close with the completion checklist.
Deliberate failure
Break
Catch Exception, log it, and continue as if nothing happened
Observe
A real error disappears and the program keeps running in a corrupted state
Repair
Catch the most specific type, handle or rethrow deliberately, and never swallow silently
Why it matters
Catch the most specific type, handle or rethrow deliberately, and never swallow silently
Completion checklist
- Distinguish checked and unchecked exceptions
- Release resources with try-with-resources
- Catch the most specific type first
Go deeper
Official references
The primary sources behind this chapter. Every claim above stays consistent with them.