Sobes.tech
Middle

How does the try-with-resources operator work in Java?

sobes.tech AI

Answer from AI

The try-with-resources operator guarantees the automatic closing of resources that implement the java.lang.AutoCloseable interface.

Working principle:

  1. In parentheses after the try keyword, resources that need to be closed are declared and/or initialized.
  2. Operations with these resources are performed within the try block.
  3. If exceptions occur in the try block or during resource initialization:
    • Exceptions are suppressed if they occur during the automatic closing of resources after the main exception in the try block.
    • The main exception that occurred in the try block or during initialization is thrown further.
  4. Regardless of whether an exception occurs or not, the close() method of each resource declared in the parentheses of try will be automatically called upon completion of the try block.
  5. Resources are closed in the reverse order of their declaration in the parentheses.

Advantages:

  • Simplifies code by removing the need for explicit calls to close() for each resource.
  • Ensures resources are closed even if exceptions occur.
  • Handles suppressed exceptions.

Example:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class TryWithResourcesExample {

    public static void main(String[] args) {
        // Opening FileReader and BufferedReader resources
        try (FileReader fr = new FileReader("example.txt");
             BufferedReader br = new BufferedReader(fr)) {

            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            // Handling exceptions, e.g., file read error
            e.printStackTrace();

            // Access suppressed exceptions (if any during closing)
            Throwable[] suppressedExceptions = e.getSuppressed();
            for (Throwable suppressed : suppressedExceptions) {
                System.err.println("Suppressed exception: " + suppressed.getMessage());
            }
        }
    }
}
How does the try-with-resources operator work in… - sobes.tech