On this page
  1. Exceptions & Resource Management
  2. Overview
  3. The Throwable Hierarchy
  4. Checked vs. Unchecked Guidance
  5. Deterministic Cleanup with try-with-resources
  6. Avoid finalize()

Exceptions & Resource Management

Prev: Generics & Type Erasure | Up: Language & OOP | Next: Lambdas, Streams & Functional Interfaces
Rel: try-with-resources, AutoCloseable, RuntimeException, finalize (Legacy), java.nio & java.io
Ref: Java 21 API — Throwable , OpenJDK JEP 421 — Deprecate Finalization
Tags: #public #java #exceptions #resources #tier/core


Overview

Java distinguishes between checked exceptions (enforced by the compiler), unchecked runtime exceptions, and JVM errors, and relies on deterministic try-with-resources rather than garbage-collector finalizers to release OS handles.

The Throwable Hierarchy

Throwable
├── Error                      (unchecked — serious JVM failures: OutOfMemoryError, StackOverflowError)
└── Exception
    ├── IOException, ...       (checked — recoverable environmental/I/O failures; must catch or declare)
    └── RuntimeException       (unchecked — programming bugs: NullPointerException, IllegalArgumentException)

Checked vs. Unchecked Guidance

Deterministic Cleanup with try-with-resources

Any resource implementing AutoCloseable (files, sockets, streams, JDBC connections) should be opened in a try (...) header. Resources close automatically in reverse declaration order, and if both the try body and close() throw, the body's exception is primary while the close() exception is preserved via getSuppressed().

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

static void copyUppercase(Path in, Path out) throws IOException {
    try (BufferedReader reader = Files.newBufferedReader(in);
         BufferedWriter writer = Files.newBufferedWriter(out)) {
        String line;
        while ((line = reader.readLine()) != null) {
            writer.write(line.toUpperCase());
            writer.newLine();
        }
    }
}

Avoid finalize()

Object.finalize() is deprecated for removal (JEP 421 ). It introduces unpredictable latency, resurrection bugs, and GC pauses. Always use AutoCloseable + try-with-resources, or java.lang.ref.Cleaner as a last-resort safety net for native memory wrappers.

Linked from

Related notes