Note that there are some explanatory texts on larger screens.

plurals
  1. POIs it possible to detect if an exception occurred before I entered a finally block?
    primarykey
    data
    text
    <p>In Java, is there an elegant way to detect if an exception occurred prior to running the finally block? When dealing with "close()" statements, it's common to need exception handling within the finally block. Ideally, we'd want to maintain both exceptions and propagate them up (as both of them may contain useful information). The only way I can think of to do this is to have a variable outside the try-catch-finally scope to save a reference to a thrown exception. Then propagate the "saved" exception up with any that occur in the finally block.</p> <p>Is there a more elegant way of doing this? Perhaps an API call that will reveal this?</p> <p>Here's some rough code of what I'm talking about:</p> <pre><code>Throwable t = null; try { stream.write(buffer); } catch(IOException e) { t = e; //Need to save this exception for finally throw e; } finally { try { stream.close(); //may throw exception } catch(IOException e) { //Is there something better than saving the exception from the exception block? if(t!=null) { //propagate the read exception as the "cause"--not great, but you see what I mean. throw new IOException("Could not close in finally block: " + e.getMessage(),t); } else { throw e; //just pass it up } }//end close } </code></pre> <p>Obviously, there are a number of other similar kludges that might involve saving the exception as an member variable, returning it from a method, etc... but I'm looking for something a bit more elegant.</p> <p>Maybe something like <code>Thread.getPendingException()</code> or something similar? For that matter, is there an elegant solution in other languages?</p> <p>This question actually spawned from comments in <a href="https://stackoverflow.com/questions/183499/is-there-a-preference-for-nested-trycatch-blocks#183572">another question</a> that raised an interesting question. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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