Loading published curriculum…

03 · Practical Java / LESSON 7 OF 102

Exceptions and resource management

Failures should be visible and resources should close predictably.

Before this lesson: Generics, List, Set, and Map

Understand the topic

Checked exceptions must be caught or declared. Unchecked exceptions often signal invalid arguments or runtime failures. Catch a narrow type and handle it meaningfully; do not ignore every Exception or convert errors into success.

Try-with-resources closes AutoCloseable resources even when work fails. Paths are relative to the process working directory. Keep internal failure details in logs, not public API responses.

EXAMPLE · JAVA

Main.java

import java.io.*;
import java.nio.file.*;
public class Main {
    public static void main(String[] args) {
        try (BufferedReader reader = Files.newBufferedReader(Path.of("tasks.txt"))) {
            System.out.println(reader.readLine());
        } catch (IOException error) {
            System.err.println("Read failed: " + error.getClass().getSimpleName());
        }
    }
}

What to expect

Create tasks.txt containing Learn SQL; the program prints that line. A missing file prints an error type.

YOUR TURN

Put it into practice

  1. 01Test missing and empty files.
  2. 02Explain why the reader closes after an exception.
  3. 03Handle malformed numeric input specifically.

Pass a quiz or complete a lab to check today’s streak. Each lesson counts once per day, including when you review it later.

UNDER THE HOOD

Build the mental model

An exception crosses call boundaries until a handler accepts responsibility for the failure.

  1. 01Use a checked exception when callers should be forced to consider recovery; use a domain-specific runtime exception when it makes the contract clearer.
  2. 02Preserve the original cause when translating an exception. Replacing it with only a generic string makes diagnosis harder.
  3. 03Resources close in reverse declaration order in try-with-resources. A cleanup exception may be suppressed behind the original failure.

A mistake worth avoiding

Catching Throwable can hide failures the application cannot safely recover from.

DEBUGGING ROOM

Something broke. Where do you look?

A missing input file is reported as a successful empty import.

Before revealing the diagnosis, write down your first investigation step.

CHECK YOUR UNDERSTANDING

What is wrong with catch (Exception e) { return true; } around a write?

Choose one answer

BUILD IT YOURSELF

Write a safe file importer

  1. 1.Read lines with try-with-resources.
  2. 2.Attach line numbers to malformed input errors.
  3. 3.Preserve file-access failures as failures.

Acceptance checklist

Lab completion is your self-report. Knowledge checks do not certify project quality.

RETRIEVE IT FROM MEMORY

When should an exception be translated into a domain error?

Revisit this lesson in three days after a successful check or lab.

Ready for the next step?

Handle a failure without hiding it or leaking a resource.

Reading is separate from passing a knowledge check or completing a lab.

Go deeper · official references