Repaso
EspaƱol
Java CoreIntermediateJV-16

What is try-with-resources for?

Options

  1. Trying several resources in parallel until one works
  2. Closing resources automatically, even after an error (Correct option)
  3. Retrying an operation again and again until it succeeds
  4. Allocating extra memory to the resource when needed

Answer

Automatically closing resources (files, connections) at the end of the block, even if an exception happens

Why

Resources such as files, database connections and sockets must be closed or they leak. The old way needed a finally block with extra try/catch.

With try (Resource r = ...) { ... }, Java calls r.close() automatically when the block ends, normally or by exception. The resource must implement AutoCloseable. Resources close in reverse order of creation.

try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
    System.out.println(br.readLine());
}   // br.close() is called automatically

Remember

Open it in the try parentheses and Java closes it for you.

Key terms

Practice this question in Repaso