Java try-with-resources
In this page:
The try-with-resources Syntax
Writing try (Resource r = new Resource()) inside the parentheses of a try block tells Java to manage that resource's lifecycle for you. The resource is opened when the try block starts and is guaranteed to be closed when it ends, whether the block finishes normally or throws an exception.
Example: The try-with-resources Syntax
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
try (FileWriter writer = new FileWriter("data.txt")) { // opened in the parentheses
writer.write("Hello");
} // closed automatically here
System.out.println("Done");
}
}
Login to try C/C++/Java/PHP code in the editor
AutoCloseable and close()
Only objects whose class implements the AutoCloseable interface (or its subtype Closeable) can be used in a try-with-resources statement, since Java needs a close() method to call automatically. Common examples include FileReader, BufferedReader, and JDBC's Connection and Statement classes.
Example: AutoCloseable and close()
class Resource implements AutoCloseable {
public void close() {
System.out.println("Resource closed");
}
}
public class Main {
public static void main(String[] args) {
try (Resource r = new Resource()) {
System.out.println("Using resource");
}
}
}
Login to try C/C++/Java/PHP code in the editor
Why It Replaces finally Cleanup
Before this syntax, closing a resource safely meant opening it before the try block and closing it in a finally block, which was verbose and easy to get wrong (forgetting a null check, or closing in the wrong order). try-with-resources removes that boilerplate entirely and closes resources in the reverse order they were opened.
Example: Why It Replaces finally Cleanup
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
FileWriter writer = new FileWriter("data.txt");
try {
writer.write("Hello");
} finally {
writer.close(); // old, verbose, error-prone way
}
}
}
Login to try C/C++/Java/PHP code in the editor
Multiple Resources
You can open several resources in one try-with-resources statement by separating their declarations with semicolons, for example try (FileReader fr = ...; BufferedReader br = ...). Java closes them automatically in reverse declaration order, so the last resource opened is the first one closed.
Example: Multiple Resources
class Resource implements AutoCloseable {
String name;
Resource(String name) { this.name = name; }
public void close() {
System.out.println(name + " closed");
}
}
public class Main {
public static void main(String[] args) {
try (Resource a = new Resource("A"); Resource b = new Resource("B")) {
System.out.println("Using both");
} // closed in reverse order: B then A
}
}
Login to try C/C++/Java/PHP code in the editor
Suppressed Exceptions
If the code inside the try block throws an exception and then closing the resource also throws, Java doesn't lose the second exception, it attaches it to the first as a "suppressed" exception, retrievable via getSuppressed(). This is more informative than the old finally-block pattern, where a close() failure could silently overwrite the original error.
Example: Suppressed Exceptions
class Resource implements AutoCloseable {
public void close() {
throw new RuntimeException("Close failed");
}
}
public class Main {
public static void main(String[] args) {
try (Resource r = new Resource()) {
throw new RuntimeException("Body failed");
} catch (RuntimeException e) {
System.out.println(e.getMessage());
for (Throwable suppressed : e.getSuppressed()) {
System.out.println("Suppressed: " + suppressed.getMessage());
}
}
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: