I have just encountered this following code:
public class TestFinally {
public static void main(String[] args) {
int returnValue = function();
System.out.println("Return value: " + returnValue);
}
public static int function() {
try {
return 1;
} catch (Exception e){
return 2;
} finally{
return 3;
}
}
}
It is without a doubt that running this code will yield an output of "Return value: 3".
However, I am curious as to:
- The mechanism of the innards in the JVM. Does anyone know if the VM actually replaces the return value on the stack by over-writing the first "return 1"? If so, where can I find more information on this.
- I have yet to find the use for a return in the finally mechanism that is used this way and allowed in the implemented
in the JVM. If this code construct is used as a means to return
error code, it is in my opinion there are better ways to log errors
or return these error codes. Has anyone found a use for such a
construct?
Many thanks in advance.
Cheers,
Vern
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…