Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple returns: Which one sets the final return value?

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.

like image 858
Daniel Rikowski Avatar asked Feb 22 '10 09:02

Daniel Rikowski


People also ask

Can you have multiple returns in a method?

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.

What should the returned value of a method match?

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.

How do you return a variable from a function?

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.


2 Answers

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 :)

like image 88
skaffman Avatar answered Sep 22 '22 13:09

skaffman


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).
like image 29
polygenelubricants Avatar answered Sep 19 '22 13:09

polygenelubricants