Try-with-Resources
Resources such as files, sockets, and database statements often implement AutoCloseable. Try-with-resources guarantees closure at the end of the statement's scope.
try (BufferedReader reader =
Files.newBufferedReader(Path.of("app.log"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
throw new RuntimeException("Unable to read log", e);
}
If both the body and close() throw, Java preserves the close failure as a suppressed exception.
Key Takeaways
- Prefer try-with-resources for
AutoCloseableresources. - Resources close in reverse declaration order.
- Suppressed exceptions preserve cleanup failures without losing the original exception.