Thursday 22 May 2014

Java's return value in try-catch-finally mechanism

Hello friends again question with try,catch and finally..i like it ...lol..

Here sample code is :

public class J2 extends J1 {

    public static int function() {
        try {
            return 1; // We think after return function complete here ...?
        } catch (Exception e) {
            return 2;
        } finally {
            return 3;      // But actually  this block execute successfully
    }
 }

    public static void main(String[] args) {
        System.out.println(function());
    }
}


I have no idea how the JVM implements it, but the simplest way to look at it (at least conceptually) would be:
  1. the return value in the "try" is pushed onto the stack,
  2. then the "finally" block is executed,
  3. the new return value is pushed onto the stack
  4. the function exits, and the return value is popped from the stack, thus ignoring the first one.


What I found in the Java language specification at least defines that your code snippet should return 3. Of course, it does not mention how the JVM should implement this, and what possible optimizations one could do.
Section 14.20.2 defines that
If execution of the try block completes abruptly for any other reason R, then the finally block is executed. Then there is a choice:
  1. If the finally block completes normally, then the try statement completes abruptly for reason R.
  2. If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).
And the start of chapter14 (section 14.1 to be more precise) specifies what a normal and abrupt completion is. For example a return with a given value is an abrupt completion.
Hence in this case, the finally block completes abruptly (reason: return with a given value), so the try will complete abruptly for the same reason (and return 3). This is confirmed in section 14.17 about the return statement as well
If evaluation of the Expression completes normally, producing a value V, then the return statement completes abruptly, the reason being a return with value V.



No comments:

Post a Comment