On this page
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
- Checked exceptions (
IOException,InterruptedException): Use when the caller can reasonably recover (retry, fall back, prompt the user). Always preserve the root cause when wrapping:throw new UncheckedIOException("Failed reading config", e);. - Unchecked exceptions (
IllegalArgumentException,IllegalStateException,NullPointerException): Use for contract violations and precondition checks (Objects.requireNonNull). - Errors: Do not catch
ErrororThrowablein normal application code; let the JVM or top-level boundary fail fast. - InterruptedException: Never swallow it silently. Either rethrow it or restore the interrupt flag with
Thread.currentThread().interrupt().
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
- tuts/java/language_and_oop/generics_and_type_erasure Linked here; links to this page; shared tags: #java, #tier
- tuts/java/language_and_oop/lambdas_streams_and_functional_interfaces Linked here; links to this page; shared tags: #java, #tier
- tuts/java/language_and_oop Linked here; links to this page; shared tags: #java
- tuts/java/builtins/AutoCloseable Linked here; shared tags: #java, #tier
- tuts/java/builtins/finalize Linked here; shared tags: #java, #tier
- tuts/java/builtins/RuntimeException Linked here; shared tags: #java, #tier
- tuts/java/builtins/try_with_resources Linked here; shared tags: #java, #tier
- tuts/java/stdlib/java_nio_and_io Linked here; shared tags: #java
- tuts/interop/java_and_c_ffm_and_jni shared tags: #java, #tier
- tuts/java/builtins/enum shared tags: #java, #tier