Note that there are some explanatory texts on larger screens.

plurals
  1. POWhen Does the Finally Block Run Relative to the Return
    primarykey
    data
    text
    <p>I stumbled across an interesting error yesterday and have since fixed it, but it still was bothering me this morning, so I would like to see if anyone can shed some light on the issue.</p> <p>The code in question:</p> <pre><code>final ResultSet rs = prepStatement.executeQuery(); try { if (!rs.next()) { throw new IllegalStateException("Expected non-empty result"); } return rs.getInt(0 + 1); } finally { rs.close(); } </code></pre> <p>Now for the part that doesn't make since. Every once in a while, the return statement will throw an exception indicating that getInt(int) has been called on a closed ResultSet. I verified that the prepared statement is not being closed anywhere in the code, and if the database was closing, I would see other errors as well. This leads me to believe that somehow, occasionally, the finally block is being executed before the return statement. The only thing I can think of is that the hotspot compiler doesn't always get this right. I'm using the Oracle JVM listed below.</p> <blockquote> <p>java version "1.7.0_45"<br> Java(TM) SE Runtime Environment (build 1.7.0_45-b18)<br> Java HotSpot(TM) 64-Bit Server VM (build 24.45-b08, mixed mode)</p> </blockquote> <p>I feel like I should mention that I have seen the host of other questions about this ordering, but they all seem to indicate that it is set in stone, where I seem to be witnessing something different.</p> <p><a href="https://stackoverflow.com/questions/15225819/try-catch-finally-return-clarification-in-java">Try-catch-finally-return clarification</a> <br> <a href="https://stackoverflow.com/questions/20164755/the-order-of-invoking-finally-block">https://stackoverflow.com/questions/20164755/the-order-of-invoking-finally-block</a> <br> <a href="https://stackoverflow.com/questions/65035/does-finally-always-execute-in-java">Does finally always execute in Java?</a> </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