⬅ Previous Topic
Java catch Multiple ExceptionsNext Topic ⮕
Java throw Keyword⬅ Previous Topic
Java catch Multiple ExceptionsNext Topic ⮕
Java throw KeywordManaging 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.
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.
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.
try (ResourceType resource = new ResourceType()) {
// use the resource
} catch (Exception e) {
e.printStackTrace();
}
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();
}
}
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.
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.
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
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()
Use try-with-resources when you are dealing with resources like:
The try-with-resources statement is more than just syntactic sugar — it enforces good habits and removes the human error from manual cleanup.
AutoCloseable
in try-with-resources?⬅ Previous Topic
Java catch Multiple ExceptionsNext Topic ⮕
Java throw KeywordYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.