Proper Ways to Close Resources in Java
The article explains best practices for safely closing resources in Java, including using finally blocks, null checks, separate try‑catch for each resource, avoiding return or System.exit in finally, not throwing exceptions from finally, and preferring try‑with‑resources with code examples.
Correct Ways to Close Resources
1. Use a finally block to ensure the close operation is always executed.
2. Before closing each resource, check that its reference is not null to avoid NullPointerException.
3. Use a separate try...catch for each resource so an exception while closing one does not prevent others from being closed.
4. Do not use return statements inside finally blocks, as they bypass remaining try / catch code.
5. Avoid calling System.exit(0) inside finally , because it terminates the JVM and the block will not run.
6. Do not throw exceptions from finally ; they will suppress any exception thrown in the try block, leading to lost information.
Reference: “Java Pitfalls: Exceptions or return statements in finally blocks cause exception loss”.
7. Prefer the try‑with‑resources statement.
Example using try‑with‑resources :
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
class WithTryResource {
public static void main(String[] args) throws IOException {
try (Scanner scanner = new Scanner(new File("testRead.txt"));
PrintWriter writer = new PrintWriter(new File("testWrite.txt"))) {
while (scanner.hasNext()) {
writer.print(scanner.nextLine());
}
}
}
}Java 9 syntax example:
private static void printFile() throws IOException {
FileInputStream input = new FileInputStream("file.txt");
try (input) {
int data = input.read();
while (data != -1) {
System.out.print((char) data);
data = input.read();
}
}
}Cognitive Technology Team
Cognitive Technology Team regularly delivers the latest IT news, original content, programming tutorials and experience sharing, with daily perks awaiting you.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.