Whether the Java finally statement is executed before or after the return

Source: Internet
Author: User
Tags finally block

I've seen it online. About exception capture mechanism in Java the finally statement in the try...catch...finally block is not certain to be executed. There are also many discussions.

First, make it clear that the following two scenarios are definitely not performed:
1). The return statement returned without execution before the try, and of course not.
2). The Try statement forces the JVM to exit with System.exit (0), and the brute force exit will not be enforced.

First look at the following code

Package Com.loongshaw;PublicClasstryreturnfinally {Publicstatic void main (String[] args) { System.out.println (Test1 ()); } public static int test1 () {int B = 1; try {System.out.println ( "try block"); return ++b;} catch (Exception e) {b = 10; System.out.println ( "catch block");} finally {++b; System.out.println ( "finally Block");} System.out.println ( "last Block"); return b;}            

If you think the result of its execution is 3, then please continue to watch, the middle recruit, haha.
Let's take a look at the results:

try blockfinally block2
    • 1
    • 2
    • 3

As you can see, the result of the above code is 2. The general idea of its finally also carried out, try also executed, clearly executed two ++b it, what happened?

This time, let's break a bit to see:
(1). When the program executes the return statement in the try, then B is still 1.

(2). When the program executes to the finally statement, the ++b,b becomes 2.

(3). At this point, we click on the B in Try...return and find that its value becomes 2.

The above results illustrate a point: the return statement executes and then the finally statement is executed, but the return statement is not returned directly, but is returned after the finally statement has been executed.

Use the following test case to enhance your understanding:

Package Com.loongshaw;PublicClasstryreturnfinally {PublicStaticvoidMain (string[] args) {System.out.println (Test2 ());} public static String test2 () {try {System.out.println ( "try block"); return test3 ();} catch (Exception e) {System.out.println ( "catch block");} finally {System.out.println ( "finally Block");} System.out.println ( "last Block"); return  "last Block";} public static String test3 () { System.out.println ( "return block"); return  "output return block";}}      

Execution Result:

try blockreturn blockfinally blockoutput return block

As a result, the Test3 () method is executed when you execute return in a try statement, its return value is stored in a temporary variable, and then the finally statement is executed.

try {                  System.out.println("try block");                return test3();               }

The final output is stored in the temporary variable return value.

return block
    • 1

Perhaps you will continue to say, if there is a return in the finally and catch, what is the case:
(1) First look at the catch with return

public static int test4() {         int b = 1; try { System.out.println("try block"); return b/0; } catch (Exception e) { System.out.println("catch block"); return ++b; } finally { b = b+ 10; System.out.println("finally block"); } }

Results

try blockcatch blockfinally block2

As can be seen, the return in Catch is the same as the try, and finally executes, but does not affect the return result in the try and catch.

(2) and then look at finally, there's return.

public static int test5() {         int b = 1; try { System.out.println("try block"); return ++b; } catch (Exception e) { ++b; System.out.println("catch block"); return b; } finally { b = b+ 10; System.out.println("finally block"); return b; } }

Results

try blockfinally block12

Visible, the return in finally returns directly, which is different from the return in the try and catch.

You may find that the last return of the Test1 () method is not executed, is not.

public static int test1() {      ...        System.out.println("last block"); return b; ...}

Typically, the situation is not performed unless a catch is triggered. Here is the modified fragment code:

 public static int test1 () {int b = 1; try {b = b/0; System.out.println ( "try block"); return ++b;} catch (Exception e) {b = 10; System.out.println ( "catch block");} finally {b = + + 10; System.out.println ( "finally Block");} System.out.println ( "last Block"); return b;            

Execution Result:

catch blockfinally blocklast block20

The above results can be used to conclude that the outermost return will be executed when the catch is triggered.

Summarize:

    1. The finally statement executes after the return of the try and catch statements executes, before returning;
    2. If there is no return in the finally statement, the result of its execution does not affect the returned value determined in the try and catch;
    3. If there is a return in the finally statement, the result of its execution is returned directly.

Whether the Java finally statement is executed before or after the return

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.