Video in progress
What is try-with-resources, and why do you need it?
Resources opened in the try (...) parentheses (anything that's AutoCloseable) are closed automatically when the block ends, even if there's an error. The problem of writing close() by hand in finally, and forgetting it, goes away.
📖 Answer
The old way:
BufferedReader r = null;
try {
r = Files.newBufferedReader(path);
return r.readLine();
} finally {
if (r != null) r.close(); // close can throw an exception too
}
The modern way:
try (BufferedReader r = Files.newBufferedReader(path)) {
return r.readLine();
}
With several resources, they're closed in reverse order:
try (Connection c = ds.getConnection();
PreparedStatement ps = c.prepareStatement(sql)) {
...
} // ps is closed first, then c
The resource is always closed, so file descriptors and DB connections don't leak. Another subtle benefit: if an error happens both inside the block and in close(), the main error isn't lost. The close error is attached to it as "suppressed" (e.getSuppressed()).
You can make your own class AutoCloseable too and use it with this syntax.
Sign up to mark studied questions and save your progress.