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.
JavaScript functions can return a single value. To return multiple values from a function, you can pack the return values as elements of an array or as properties of an object.
Any method that is not declared void must contain a return statement with a corresponding return value, like this: return returnValue; The data type of the return value must match the method's declared return type; you can't return an integer value from a method declared to return a boolean.
To return a value from a function, you must include a return statement, followed by the value to be returned, before the function's end statement. If you do not include a return statement or if you do not specify a value after the keyword return, the value returned by the function is unpredictable.
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):
A try statement with a finally block is executed by first executing the try block. Then there is a choice:
- If execution of the try block completes normally, [...]
- If execution of the try block completes abruptly because of a throw of a value V, [...]
- If execution of the try block completes abruptly for any other reason R, then the finally block is executed. Then there is a choice:
- If the finally block completes normally, [...]
- If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With