Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If the <code>return</code> in the <code>try</code> block is reached, it transfers control to the <code>finally</code> block, and the function eventually returns normally (not a throw).</p> <p>If an exception occurs, but then the code reaches a <code>return</code> from the <code>catch</code> block, control is transferred to the <code>finally</code> block and the function eventually returns normally (not a throw).</p> <p>In your example, you have a <code>return</code> in the <code>finally</code>, and so regardless of what happens, the function will return <code>34</code>, because <code>finally</code> has the final (if you will) word.</p> <p>Although not covered in your example, this would be true even if you didn't have the <code>catch</code> and if an exception were thrown in the <code>try</code> block and <em>not</em> caught. By doing a <code>return</code> from the <code>finally</code> block, you suppress the exception entirely. Consider:</p> <pre><code>public class FinallyReturn { public static final void main(String[] args) { System.out.println(foo(args)); } private static int foo(String[] args) { try { int n = Integer.parseInt(args[0]); return n; } finally { return 42; } } } </code></pre> <p>If you run that without supplying any arguments:</p> <pre>$ java FinallyReturn</pre> <p>...the code in <code>foo</code> throws an <code>ArrayIndexOutOfBoundsException</code>. But because the <code>finally</code> block does a <code>return</code>, that exception gets suppressed.</p> <p>This is one reason why it's best to avoid using <code>return</code> in <code>finally</code>.</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