Given this code:
String test() {
try {
return "1";
} finally {
return "2";
}
}
Do the language specifications define the return value of a call to test()
? In other words: Is it always the same in every JVM?
In the Sun JVM the return value is 2
, but I want to be sure, that this is not VM-dependant.
Yes, the language spec defines that "2" is the result. If a VM does it differently, it's not spec-compliant.
Most compilers will complain about it. Eclipse, for example, will claim that the return block will never be executed, but it's wrong.
It's shockingly bad practice to write code like that, don't ever do it :)
Yes, the Java Language Specification is very clear on this issue (14.20.2):
The finally block will always be executed except in the following example:
In this case, the JVM will stop, without executing the
finally
block.So in your example, the return value will be
2
.After reading the ByteCode of program, the code is as follows:
The finally block statements is inlined before the return statement of try block, so the return from the finally block executes first and the original return statement never does.
For Program:
It converts to:
And For program: with catch block:
Converts to:
Note: Complied using JDK 1.7 & Decompiled using Cavaj.
You can refer the below link. I hope it will provide all details:
http://www.programmerinterview.com/index.php/java-questions/will-finally-run-after-return/
It says finally block will always executes even try or catch block has return statement. And if finally block also has return statement then this will override the return statement which is inside try or catch block and in this case any exception thrown in try/catch will be discarded (bad approach).
Yes, if you return something from the
finally
block, it will replace whatever you might have returned from thetry
orcatch
block.The same is true also for exceptions. If you throw something in the
finally
block, that exception will replace whatever exception was thrown in thetry
orcatch
block. So be careful to never throw something in thefinally
block, because it may hide the original reason for a failure.