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
620 views
in Technique[技术] by (71.8m points)

java - Try , finally execution flow when return is in try block

When try , finally combination is used, in try if there is a return statement.Why is finally block executed first?


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

    public static int test()
    {
        try {  
                //return 0;  
                return 100;
        }  
        finally {  
            System.out.println("finally trumps return.");
        }
    }
}

In the above code please tell me the flow of execution. I know that finally will be executed mandatorily after the try block.But in try block, return staatement will take the control to main class. In that case how will the control come to finally block?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

What do you mean by "first"?

The finally runs before execution leaves the method. When else should it run? It is, after all, part of the method.

But if you have

int x = 1;
try{
   return x;
} finally {
   x = x + 1;
}

then the method will still return 1. So the return statement does get executed before the finally block in a way (to determine the return value).

If the question is why the finally block is executed at all, well, that's what they are for: To "finally" run after the "try" block is done, no matter what.

But in try block, return statement will take the control to main class. In that case how will the control come to finally block?

How? Well, that's just how the language (and runtime) work.

Before control flow is returned to the calling method, the finally block is executed.

It technically even has the option to change the return value (by having its own return statement), but that is highly discouraged.


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

...