Try-with-resources
TL;DR
- Try-with-Resources (introduced in Java 7) automatically closes resources (like files, sockets) when the
tryblock finishes. - It eliminates the need for verbose, nested
finallyblocks to close resources. - A resource can be used in this construct only if its class implements the
java.lang.AutoCloseableinterface.
Concept
Before Java 7, properly closing a file required a try block, a catch block, and a finally block. Inside the finally block, you had to call file.close(). But close() itself throws an IOException, so you had to wrap the close() call in another nested try-catch block. It was notoriously ugly.
Try-with-resources uses parentheses try (...) to declare resources. When execution leaves the try block (whether normally or via an exception), the JVM automatically calls the close() method on those resources in the reverse order of their creation.
Examples
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TryWithResourcesExample {
public static void main(String[] args) {
// The resource is declared inside the parentheses.
// It will be closed automatically at the end.
try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
String line = br.readLine();
System.out.println(line);
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
} // NO FINALLY BLOCK NEEDED!
// --- Declaring Multiple Resources ---
/*
try (
FileReader fr = new FileReader("in.txt");
FileWriter fw = new FileWriter("out.txt")
) {
// Do IO work
} catch (IOException e) { ... }
*/
}
}
Interview Questions
Q: What happens if both the try block and the automatic close() method throw an exception?
A: This is a classic problem. If the try block throws Exception A, and while auto-closing, the resource throws Exception B, Java suppresses Exception B. Exception A is thrown to the caller, and Exception B is added to Exception A’s list of “Suppressed Exceptions”. You can access Exception B by calling ExceptionA.getSuppressed().
Q: Can you use custom classes in a try-with-resources statement?
A: Yes, absolutely. To do so, your custom class must implement the AutoCloseable interface (or Closeable), which forces you to override the public void close() throws Exception method. Once implemented, you can declare your custom object inside the try (...) parentheses.