views:

235

answers:

4

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.

+15  A: 

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

skaffman
I refrained from it the minute I thought of that, but still I was curious :)
DR
+2  A: 

The finally block will always be executed except in the following example:

String test() {
    try {
        System.exit(0);
    } finally {
        return "2";
    }
}

In this case, the JVM will stop, without executing the finally block.

So in your example, the return value will be 2.

romaintaz
+2  A: 

Yes, if you return something from the finally block, it will replace whatever you might have returned from the try or catch 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 the try or catch block. So be careful to never throw something in the finally block, because it may hide the original reason for a failure.

Esko Luontola
+8  A: 

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).
polygenelubricants