Video in progress

What is try-with-resources, and what makes it better than a plain try-finally?

It is syntax that automatically closes the resources opened in the try (...) parentheses when the block ends. A resource must implement AutoCloseable; close() is called even if an exception is thrown.

📖 Answer

Before Java 7 you wrote it like this:

BufferedReader br = null;
try {
    br = new BufferedReader(new FileReader("a.txt"));
    System.out.println(br.readLine());
} finally {
    if (br != null) br.close(); // close can throw too...
}

Now:

try (var br = Files.newBufferedReader(Path.of("a.txt"))) {
    System.out.println(br.readLine());
}

It is shorter and more resistant to mistakes. If an exception is thrown both inside the try and in close(), the main exception is not lost: the one from close() gets attached to it as "suppressed".

You can open several resources separated by semicolons; they are closed in reverse order. Since Java 9 you can also put an effectively final variable declared outside into the parentheses: try (br) { ... }.