Files, database connections and network streams must be closed after use. Forgetting to close them causes leaks, locked files and slow applications. Before Java 7, closing was done in a finally block, which was long and easy to get wrong. try-with-resources does it for you.
The old way
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("courses.txt"));
System.out.println(reader.readLine());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) reader.close();
}
The new way
try (BufferedReader reader = new BufferedReader(new FileReader("courses.txt"))) {
System.out.println(reader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
The resource in the brackets is closed automatically when the block ends, even if an exception is thrown. Several resources can be listed, separated by semicolons; they close in the reverse order they were opened.
What makes a resource
A resource must implement AutoCloseable (or its subtype Closeable). Most I/O classes, JDBC connections and statements do.
Suppressed exceptions
If the block throws an exception and closing also fails, the close exception is attached to the first one as a suppressed exception. Call e.getSuppressed() to read it. The old finally approach could hide the first error, which was worse.
Interview tip
Explain why try-with-resources is safer than finally blocks, and give one example from a database or file task you have written.
Related: exception handling in Java, Java Optional explained and Java generics explained.
These topics are practised with projects and mock interviews in our Java Full Stack course in Bangalore.
Book a free demo class at our BTM Layout centre, and ask a counsellor for batch details.
