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.
<pre><code> String foo = "bar"; </code></pre>
-
João
-
João