Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I prefer the second one. Why? If both <code>read()</code> and <code>close()</code> throw exceptions, one of them could be lost. In the first construction, the exception from <code>close()</code> overrides the exception from <code>read()</code>, while in the second one, the exception from <code>close()</code> is handled separately.</p> <hr> <p><strong>As of Java 7, the <a href="https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html" rel="nofollow noreferrer">try-with-resources construct</a> makes this much simpler.</strong> To read without caring about exceptions:</p> <pre><code>try (FileReader fr = new FileReader("SomeFile.txt")) { fr.read(); // no need to close since the try-with-resources statement closes it automatically } </code></pre> <p>With exception handling:</p> <pre><code>try (FileReader fr = new FileReader("SomeFile.txt")) { fr.read(); // no need to close since the try-with-resources statement closes it automatically } catch (IOException e) { // Do exception handling log(e); // If this catch block is run, the FileReader has already been closed. // The exception could have come from either read() or close(); // if both threw exceptions (or if multiple resources were used and had to be closed) // then only one exception is thrown and the others are suppressed // but can still be retrieved: Throwable[] suppressed = e.getSuppressed(); // can be an empty array for (Throwable t : suppressed) { log(suppressed[t]); } } </code></pre> <p>Only one try-catch is needed and all exceptions can be safely handled. You can still add a <code>finally</code> block if you like, but there is no need to close the resources.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload