Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
498 views
in Technique[技术] by (71.8m points)

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

I have just encountered this following code:

public class TestFinally {
    public static void main(String[] args) {
        int returnValue = function();

        System.out.println("Return value: " + returnValue);
    }

    public static int function() {
        try {
            return 1;
        } catch (Exception e){
            return 2;
        } finally{
            return 3;
        }
    }
}

It is without a doubt that running this code will yield an output of "Return value: 3".

However, I am curious as to:

  1. The mechanism of the innards in the JVM. Does anyone know if the VM actually replaces the return value on the stack by over-writing the first "return 1"? If so, where can I find more information on this.
  2. I have yet to find the use for a return in the finally mechanism that is used this way and allowed in the implemented in the JVM. If this code construct is used as a means to return error code, it is in my opinion there are better ways to log errors or return these error codes. Has anyone found a use for such a construct?

Many thanks in advance.

Cheers, Vern

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...