Skip to main content
Module 5 · Lesson 2 of 212/22 in the course~14 min
Module lessons (2/2)

Try-with-resources and AutoCloseable

Lesson preview5 hands-on exercises readyCourse Java · Module 5 — Exception Management

Guaranteed automatic closure in LIFO order, AutoCloseable, suppressed exceptions and prevention of resource leaks.

What you'll learn in this lesson

  • Replace the verbose manual closing try / finally blocks with the try-with-resources construct (Java 7+).
  • Implement the AutoCloseable interface to make any custom resource securely closeable.
  • Understand the LIFO order of closing multiple resources and the suppressed exceptions mechanism (getSuppressed()).

Overview

Unlike memory on objects (reclaimed by the garbage collector), system resources such as open files, JDBC connections, sockets and ExecutorService must be deterministically closed immediately after use.

With the old finally, you had to handle possible NullPointerException and risked masking the main exception with a possible error inside close(). With try (Risorsa r = ...), the JVM automatically generates a perfect and safe finally:

Sections covered in this lesson

  1. 11. Why the finally Manual Was Fragile vs try-with-resources
  2. 22. Implement AutoCloseable on Custom Resources
  3. 33. Multiple Resources and Reverse Order (LIFO)
  4. 44. Effectively Final Variables (Java 9+) and Suppressed Exceptions
  5. 5Try it yourself
Pro Lesson · Module 5 — Exception Management

Unlock "Try-with-resources and AutoCloseable" and the full Course Java curriculum

Guaranteed automatic closure in LIFO order, `AutoCloseable`, suppressed exceptions and prevention of resource leaks.

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in Course Java plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.