Trywithresources
Try-with-resources is a Java language feature introduced in Java 7 that automates the management of resources such as streams, files, and sockets. Any resource that implements AutoCloseable (or Closeable) declared in the try parentheses is automatically closed when the block exits, reducing boilerplate and preventing resource leaks.
How it works: Resources are opened in the try header and closed automatically in reverse order when
Syntax: try (ResourceType r = expression; ResourceType r2 = expression2) {
}
Example: try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
while ((line = br.readLine()) != null) {
}
} catch (IOException e) {
}
Notes: The resources must implement AutoCloseable (or Closeable). They are local to the try-with-resources statement and