Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Exceptions thrown in finally block suppress the exception thrown earlier in try or catch block.</p> <p>Java 7 example: <a href="http://ideone.com/0YdeZo" rel="noreferrer">http://ideone.com/0YdeZo</a></p> <p>From <a href="http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html#suppressed-exceptions" rel="noreferrer">Javadoc's</a> example:</p> <hr> <pre><code>static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException { BufferedReader br = new BufferedReader(new FileReader(path)); try { return br.readLine(); } finally { if (br != null) br.close(); } } </code></pre> <blockquote> <p>However, in this example, if the methods readLine and close both throw exceptions, then the method readFirstLineFromFileWithFinallyBlock throws the exception thrown from the finally block; the exception thrown from the try block is suppressed.</p> </blockquote> <hr> <p>The new <code>try-with</code> syntax of Java 7 adds another step of exception suppression: Exceptions thrown in try block suppress those thrown earlier in try-with part.</p> <p>from same example:</p> <pre><code>try ( java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName); java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset) ) { for (java.util.Enumeration entries = zf.entries(); entries.hasMoreElements();) { String newLine = System.getProperty("line.separator"); String zipEntryName = ((java.util.zip.ZipEntry)entries.nextElement()).getName() + newLine; writer.write(zipEntryName, 0, zipEntryName.length()); } } </code></pre> <blockquote> <p>An exception can be thrown from the block of code associated with the try-with-resources statement. In the above example, an exception can be thrown from the try block, and up to two exceptions can be thrown from the try-with-resources statement when it tries to close the ZipFile and BufferedWriter objects. If an exception is thrown from the try block and one or more exceptions are thrown from the try-with-resources statement, then those exceptions thrown from the try-with-resources statement are suppressed, and the exception thrown by the block is the one that is thrown by the writeToFileZipFileContents method. You can retrieve these suppressed exceptions by calling the Throwable.getSuppressed method from the exception thrown by the try block.</p> </blockquote> <hr> <p>In code from question, each block is plainly discarding the old exception, not even logging it, not good when you are trying to resolve some bugs: </p> <p><a href="http://en.wikipedia.org/wiki/Error_hiding" rel="noreferrer">http://en.wikipedia.org/wiki/Error_hiding</a></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