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:
- In parentheses after the
trykeyword, resources that need to be closed are declared and/or initialized. - Operations with these resources are performed within the
tryblock. - If exceptions occur in the
tryblock or during resource initialization:- Exceptions are suppressed if they occur during the automatic closing of resources after the main exception in the
tryblock. - The main exception that occurred in the
tryblock or during initialization is thrown further.
- Exceptions are suppressed if they occur during the automatic closing of resources after the main exception in the
- Regardless of whether an exception occurs or not, the
close()method of each resource declared in the parentheses oftrywill be automatically called upon completion of thetryblock. - 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());
}
}
}
}