Chapter 10 of 16Foundation

Exceptions and Resource Management

Separate happy-path code from failure handling, preserve causes, and close resources safely with try-with-resources.

25 minJava 21
01

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
02

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.

03

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.

  1. 01Throwable hierarchy
  2. 02Checked vs unchecked
  3. 03try / catch / finally
  4. 04try-with-resources
  5. 05Throw specific types
  6. 06Catch narrow first
04

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

2 focused examples
01

try-with-resources

The reader closes automatically, even if readLine throws.

Read.java
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.

02

Custom exception

Extend RuntimeException for a domain error that callers did not have to declare.

DomainError.java
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.

05

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

  1. Break

    Catch Exception, log it, and continue as if nothing happened

  2. Observe

    A real error disappears and the program keeps running in a corrupted state

  3. 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
06

Go deeper

Official references

The primary sources behind this chapter. Every claim above stays consistent with them.