Note that there are some explanatory texts on larger screens.

plurals
  1. POTry-catch-finally-return clarification
    primarykey
    data
    text
    <p>By reading all the questions already asked in this forum related to the topic above (see title), I thoroughly understand that <code>finally</code> gets always called. (except from <code>System.exit</code> and infinite loops). However, I would like to know if a <code>return</code> is called in a catch block and then another <code>return</code> is called from the finally block.</p> <p>For example:</p> <pre><code>public static void main(String[]args) { int a = new TestClass().absorbeTheValue(); } int absorbeTheValue() { try { int a = 10/0; if (a &gt; 0) return 4; } catch(Exception e) { return 45; } finally { return 34; } } </code></pre> <p>So here the output (when the method is called) is going to be 34 in any case. It means that finally always gets run. I think though that the other "returns" are not run at all. In many posts I found the fact that finally write the content over what had been already written by the catch clause return. My understanding is that as soon as the return value in the catch clause is about to be evaluated, the control flow pass to the finally clause which having in turn another return, this time the return will be evaluated without passing control back to the catch clause. In this way the only <code>return</code> called at runtime will be the finally return. Do you agree with that?</p> <p>A <code>return</code> in <code>finally</code> does not pass back the control to the program but returns the value and terminates the method. Can we say so?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    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