Search code examples
javareturnfinally

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.


Solution

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