Lesson 3 of 616 minModule progress 0%

Module 9: Exceptions, Validation, and Debugging

Try-with-Resources and AutoCloseable

Use try-with-resources so files, scanners, and streams close automatically.

Author

Java Learner Editorial Team

Reviewer

Technical review by Java Learner

Last reviewed

2026-04-17

Java version

Java 25 LTS

How this lesson was prepared: AI-assisted draft, manually edited for clarity, and checked against current Java documentation and runnable examples.

Learning goals

  • Use try-with-resources for closable objects
  • Recognize `AutoCloseable` types quickly
  • Write less cleanup code without losing safety

Try-with-resources is the default for files, readers, streams, and scanners: It closes resources automatically when the block ends.

This is cleaner than manual finally cleanup: The code is shorter, safer, and harder to get wrong.

The resource must implement AutoCloseable: Many core Java IO and database classes already do.

Practical rule: If you opened something that needs closing, try-with-resources should be your first move.

Runnable examples

Scanner closes automatically

import java.util.Scanner;

try (Scanner scanner = new Scanner("Ada\n")) {
    System.out.println(scanner.nextLine());
}

Expected output

Ada

Mini exercise

Use try-with-resources with a `Scanner` that reads from a string, then print the first token.

Summary

  • Try-with-resources reduces cleanup bugs.
  • It works with `AutoCloseable` types.
  • Use it by default for resources that must be closed.

Next step

Next, design custom exceptions that carry meaning instead of throwing generic failures everywhere.

Sources used

Advertisement

Lesson check

What must a resource support to work in try-with-resources?

Next lesson →