This question already has an answer here:
By reading all the questions already asked in this forum related to the topic above (see title), I thoroughly understand that finally
gets always called. (except from System.exit
and infinite loops). However, I would like to know if a return
is called in a catch block and then another return
is called from the finally block.
For example:
public static void main(String[]args) {
int a = new TestClass().absorbeTheValue();
}
int absorbeTheValue() {
try {
int a = 10/0;
if (a > 0) return 4;
} catch(Exception e) {
return 45;
} finally {
return 34;
}
}
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 return
called at runtime will be the finally return. Do you agree with that?
A return
in finally
does not pass back the control to the program but returns the value and terminates the method. Can we say so?
If the
return
in thetry
block is reached, it transfers control to thefinally
block, and the function eventually returns normally (not a throw).If an exception occurs, but then the code reaches a
return
from thecatch
block, control is transferred to thefinally
block and the function eventually returns normally (not a throw).In your example, you have a
return
in thefinally
, and so regardless of what happens, the function will return34
, becausefinally
has the final (if you will) word.Although not covered in your example, this would be true even if you didn't have the
catch
and if an exception were thrown in thetry
block and not caught. By doing areturn
from thefinally
block, you suppress the exception entirely. Consider:If you run that without supplying any arguments:
...the code in
foo
throws anArrayIndexOutOfBoundsException
. But because thefinally
block does areturn
, that exception gets suppressed.This is one reason why it's best to avoid using
return
infinally
.Here is some code that show how it works.
The results is: