Java try-with-resources Statement
Automatic Resource Management
Managing system resources like files, sockets, or database connections is a critical responsibility in programming. Forgetting to close them can lead to memory leaks or locked resources. That’s where Java’s try-with-resources steps in — an elegant construct that automates resource management and simplifies cleanup.
What is try-with-resources in Java?
The try-with-resources
statement is a special form of the try
statement that ensures each resource is closed automatically at the end of the statement. Introduced in Java 7, it eliminates the need for verbose finally
code blocks to close resources.
Key Requirement
The resource must implement the java.lang.AutoCloseable
interface (or java.io.Closeable
for older IO classes). Most Java IO and JDBC classes already do.
Basic Syntax
try (ResourceType resource = new ResourceType()) {
// use the resource
} catch (Exception e) {
e.printStackTrace();
}
Classic Example Without try-with-resources
Before Java 7, developers had to close resources manually, typically in a finally
block.
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("input.txt"));
System.out.println(reader.readLine());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Same Example With try-with-resources
try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"))) {
System.out.println(reader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
Hello from file!
Notice how there's no need to explicitly close the reader. It’s handled behind the scenes — reliably and cleanly.
Multiple Resources in try-with-resources
You can manage more than one resource by separating them with semicolons in the try block.
try (
BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))
) {
String line = reader.readLine();
writer.write("Copied: " + line);
} catch (IOException e) {
e.printStackTrace();
}
This structure ensures writer.close()
and reader.close()
are both called, in reverse order of their creation.
Custom Resource with AutoCloseable
You can create your own resource class by implementing AutoCloseable
.
class MyResource implements AutoCloseable {
public void doSomething() {
System.out.println("Working with MyResource");
}
@Override
public void close() {
System.out.println("Closing MyResource");
}
}
public class Test {
public static void main(String[] args) {
try (MyResource res = new MyResource()) {
res.doSomething();
}
}
}
Working with MyResource
Closing MyResource
What Happens on Exceptions?
If an exception is thrown inside the try block, the resource is still closed before the catch or finally block is executed. You can even catch suppressed exceptions (thrown during close()
) using Throwable.getSuppressed()
.
class FaultyResource implements AutoCloseable {
public void use() {
throw new RuntimeException("Something went wrong in use()");
}
@Override
public void close() {
throw new RuntimeException("Something went wrong in close()");
}
}
public class SuppressedExample {
public static void main(String[] args) {
try (FaultyResource res = new FaultyResource()) {
res.use();
} catch (Exception e) {
System.out.println("Caught: " + e.getMessage());
for (Throwable suppressed : e.getSuppressed()) {
System.out.println("Suppressed: " + suppressed.getMessage());
}
}
}
}
Caught: Something went wrong in use()
Suppressed: Something went wrong in close()
Advantages of try-with-resources
- Fewer lines of code
- Automatic and safe resource cleanup
- Support for multiple resources
- Prevents common memory/resource leaks
When Should You Use It?
Use try-with-resources when you are dealing with resources like:
- File Readers/Writers
- Buffered Streams
- Database Connections and Statements
- Socket Streams
- Your own AutoCloseable classes
Conclusion
The try-with-resources statement is more than just syntactic sugar — it enforces good habits and removes the human error from manual cleanup.