What is try-with-resources in Java, and how does it differ from closing a resource in a finally block?
Try-with-resources is a way of writing a try block that closes the things it opened, and it does it for you.
The old way was to open the resource, use it, and then close it in a finally block. That worked, but it took a lot of lines and it was easy to forget the closing when there was more than one resource, or when the code between the opening and the closing was long.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
public class Main {
public static void main(String[] args) throws IOException {
// The old way, with the closing in a finally block.
BufferedReader reader = new BufferedReader(new StringReader("first line"));
try {
System.out.println("old : " + reader.readLine());
} finally {
reader.close();
}
// The new way. The reader is closed for you.
try (BufferedReader other = new BufferedReader(new StringReader("second line"))) {
System.out.println("new : " + other.readLine());
}
}
}
The difference is that the new way is shorter, it is hard to get wrong, and it closes the resource even if the body throws. It also handles the case that the old way often got wrong, which is that the closing happens even when an exception was thrown halfway through the body.
The next question in this topic looks at what happens when there is more than one resource.