Should .close() be put in finally block or not?

The following are 3 different ways to close a output writer. The first one puts close() method in try clause, the second one puts close in finally clause, and the third one uses a try-with-resources statement. Which one is the right or the best?

//close() is in try clause
try {
	PrintWriter out = new PrintWriter(
			new BufferedWriter(
			new FileWriter("out.txt", true)));
	out.println("the text");
	out.close();
} catch (IOException e) {
	e.printStackTrace();
}
//close() is in finally clause
PrintWriter out = null;
try {
	out = new PrintWriter(
		new BufferedWriter(
		new FileWriter("out.txt", true)));
	out.println("the text");
} catch (IOException e) {
	e.printStackTrace();
} finally {
	if (out != null) {
		out.close();
	}
}
//try-with-resource statement
try (PrintWriter out2 = new PrintWriter(
			new BufferedWriter(
			new FileWriter("out.txt", true)))) {
	out2.println("the text");
} catch (IOException e) {
	e.printStackTrace();
}

Answer

Because the Writer should be closed in either case (exception or no exception), close() should be put in finally clause.

From Java 7, we can use try-with-resources statement.

2 thoughts on “Should .close() be put in finally block or not?”

  1. Well after peeking at the OpenJDK source of the PrintWriter.close() and BuferedWriter.close(), they actually call the close() of the chained Writer (which IMHO, it is not an obvious interpretation of the javadoc statement “releases any system resources associated with it”).

    So, both last 2 solutions are correct.
    Happy holidays!

  2. Nice, but In any of the versions how is the FileWriter closed ? (Doesn’t it suffer from a file descriptor leak problem?)

Leave a Comment