When does a finally block run? Why is try-with-resources preferred for closing files and connections?
Show the explanation
finally runs after the try (and any matching catch) whether or not an exception was thrown, and even after a return. It is skipped only if the JVM stops (System.exit, a crash) or the thread never finishes.
Manual cleanup in finally is verbose and easy to get wrong (null checks, and an exception from close() can hide the original one). try-with-resources (Java 7+) closes any AutoCloseable automatically, in reverse order of opening, and keeps the original exception — exceptions from close() are attached as suppressed:
try (BufferedReader in = Files.newBufferedReader(Path.of("marks.csv"));
BufferedWriter out = Files.newBufferedWriter(Path.of("report.txt"))) {
String line;
while ((line = in.readLine()) != null) out.write(line.toUpperCase() + "\n");
} catch (IOException e) {
System.err.println("Could not process file: " + e.getMessage());
} // out is closed, then in - no finally neededOne trap worth mentioning: a return inside finally overrides the try's return value and swallows any exception, so never return from finally.
Original UniCircle question. Last reviewed 22 Oct 2026.
