Java › Exceptions
What is the correct usage of try-with-resources, and how does it automatically ensure a resource's close() method is called even if an exception occurs?
IntermediateAnswer
try-with-resources (any resource implementing AutoCloseable, declared within the try's parentheses) automatically calls the resource's close() method when the try block exits, whether normally or via an exception, eliminating the verbose and error-prone manual try-finally pattern previously required to guarantee resource cleanup -- multiple resources can be declared together (closed in reverse declaration order), and if both the try block's code AND the automatic close() call throw exceptions, the original exception is preserved as the primary one with the close()-triggered exception attached as a suppressed exception, accessible via getSuppressed().
// Modern try-with-resources: automatic, guaranteed cleanup
try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
String line = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
// reader.close() is called automatically, even if readLine() throws
// Old, verbose, error-prone equivalent
BufferedReader reader = new BufferedReader(new FileReader("data.txt"));
try {
String line = reader.readLine();
} finally {
reader.close(); // easy to forget, or to get wrong if this itself throws
}Real-world example A file-processing method using try-with-resources for both a FileInputStream and a BufferedReader chained together guarantees both are properly closed in the correct reverse order even if reading throws an exception midway through, eliminating an entire category of resource leak bugs common with manual try-finally cleanup code.