Try With Resources
Try With Resources
A school program needs reliable data and clear rules. Try-with-resources closes resources implementing AutoCloseable when the block exits. It reduces cleanup mistakes even when processing throws an exception.
Understand
Try-with-resources closes resources implementing AutoCloseable when the block exits.
Apply
Trace the Java example, predict its output and explain the result before running it.
Avoid mistakes
Resources close in reverse declaration order. A close failure can be suppressed when a body failure is already being propagated.
Try With Resources
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.
Important boundaries and mistakes
Resources close in reverse declaration order. A close failure can be suppressed when a body failure is already being propagated.
Try the school example
Before running this Java program, write down each line you expect to see. Identify the value, branch, object or exception responsible for each line. Then explain whether the following assumption is valid: Resources close in reverse declaration order.
Java 17 · Main.java · complete practice program
public class Main {
public static void main(String[] args) {
try (java.util.Scanner input = new java.util.Scanner("72")) {
System.out.println(input.nextInt());
}
}
}
Worked answer and reasoning
Java 17 · Main.java · source repeated for this answer
public class Main {
public static void main(String[] args) {
try (java.util.Scanner input = new java.util.Scanner("72")) {
System.out.println(input.nextInt());
}
}
}
Expected output
72Try-with-resources closes resources implementing AutoCloseable when the block exits. It reduces cleanup mistakes even when processing throws an exception.
Resources close in reverse declaration order. A close failure can be suppressed when a body failure is already being propagated.
Run with javac Main.java, then java Main. The declaration of Main names the class; main starts the example, and println writes a complete output line.
Check your understanding
Check a common mistake
What to remember
Try-with-resources closes resources implementing AutoCloseable when the block exits. It reduces cleanup mistakes even when processing throws an exception. Resources close in reverse declaration order. A close failure can be suppressed when a body failure is already being propagated.
Related explanations: Java Variables, Java If Statement - Syntax and Examples, Java Class - Blueprint of Objects, Exceptions in Java Introduction.
Supporting documentation: Official Java learning guide and Java 17 language specification.
Reaching the recap and completing the quizzes are separate milestones.