Try-With-Resources is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. By using this syntax, Java guarantees that each resource will be closed at the end of the statement, even if an exception occurs. This eliminates the need for manual finally blocks for cleanup.
Before Try-With-Resources, we had to manually close resources in a finally block. This often led to "Verbosity" and nested try-catches just to close a file.
The "Boilerplate" Code (Pre-Java 7):
Scanner s = null;
try {
s = new Scanner(new File("test.txt"));
} catch (FileNotFoundException e) { ... }
finally {
if (s != null) s.close(); // Very easy to forget!
}
In the new syntax, you declare the resource inside parentheses () immediately after the try keyword. The scope of the resource is limited to the try block, and it is closed automatically as soon as the block exits.
How does Java know which objects it can "Auto-close"? Any class used in a Try-With-Resources must implement the java.lang.AutoCloseable (or its sub-interface java.io.Closeable).
Most built-in Java classes that deal with I/O already implement this interface:
Scanner, BufferedReader, BufferedWriterFileInputStream, FileOutputStreamjava.sql.Connection, Statement, ResultSetYou can manage multiple resources in a single try block by separating them with a semicolon (;). They will be closed in the **reverse order** in which they were opened.
try (BufferedReader br = new BufferedReader(new FileReader("in.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("out.txt"))) {
// Logic here
} // bw closes first, then br closes.
One major advantage of Try-With-Resources is how it handles Suppressed Exceptions. If an exception occurs in the try block AND another exception occurs while closing the resource:
getSuppressed() method.In the old finally way, the closing exception would "overwrite" the real error, making debugging impossible!
This example shows how to create your own class that works with Try-With-Resources.
In Java 7/8, you had to declare the resource inside the try parentheses. In Java 9, if you already have a final (or effectively final) resource variable, you can just use the variable name.
Scanner sc = new Scanner(System.in);try (sc) { // Valid in Java 9+ // code }
Q: What is the primary benefit of Try-With-Resources?
A: It ensures resource safety by preventing memory leaks and makes the code cleaner by removing the need for manual finally blocks and null checks.
Q: Can we use a class that doesn't implement AutoCloseable in Try-With-Resources?
A: No. The compiler will throw an error stating that the resource type does not implement java.lang.AutoCloseable.
Q: In what order are multiple resources closed?
A: They are closed in reverse order of their declaration (LIFO - Last In, First Out).
The Try-With-Resources statement is a hallmark of modern, professional Java. It handles the "dirty work" of resource management, allowing you to focus on the core logic of your application. If you are working with I/O or Databases, this is no longer an optional feature—it is a requirement for writing high-quality code.
Next: Introduction to Multi-Threading →