Is the Java finally statement executed before or after the return?

Source: Internet
Author: User
Tags finally block

There are a lot of people on the Internet to discuss the exception capture mechanism in Java try...catch...finally The finally statement in the block is bound to be executed? A lot of people say no, of course their answer is right, after I have tried, there are at least two cases in which the finally statement will not be executed:

(1) The Try statement is not executed, as returned before the try statement, so that the finally statement does not execute, which also shows that the finally statement is executed by the necessary rather than sufficient condition is: the corresponding Try statement must be executed to.

(2) There is system.exit (0) in the try block, such a statement, System.exit (0), terminates the Java Virtual Machine JVM, even the JVM is stopped, all is finished, and the finally statement is not executed.

Of course, there are a lot of people who explore the relationship between the execution of the finally statement and return, it's confusing to know if the finally statement is executed before the return of the try or after? I am also a confused, I think their statement is not correct, I think it should be: thefinally statement is executed after the return statement of the try, return returned before the execution . This kind of argument is a bit contradictory, perhaps I am not very clear, the following I give some of the results of their own experiments and examples to support, there are any questions to welcome the proposed.

1. The finally statement executes after the return statement is executed.
PublicClassFinallyTest1 {PublicStaticvoidMain (string[] args) {System.out.println (test1 ());}PublicStaticint Test1 () {int b = 20; try {System.out.println ("try block" ); return B + = 80;} catch (Exception e) {System.out.println ("Catch block") Span style= "color: #000000"); } finally {System.out.println ("finally block" if (b > 25 b); }} return b;}}       

The operating result is:

Try blockfinally blockb>25, b = 100100  

Indicates that the return statement has executed and then executes the finally statement, but does not return directly, but waits until the finally statement is finished and returns the result.

If this example is not considered sufficient to illustrate the situation, then add an example to reinforce the conclusion that:

PublicClassFinallyTest1 {PublicStaticvoid main (string[] args) {System.out.println (test11 ());} public static String Test11 () {try {System.out.println ("try block" return test12 ();} finally {System.out.println ("finally block" public static String Test12 () {System.out.println ("return statement" return "after Return" ;}}      

The result of the operation is:

Try blockreturn statementfinallyreturn    

Indicates that the return statement in the try was executed first but did not return immediately, until the finally execution is finished

Here you might think: if there is a return statement in Finally, is it just return, and the return in the try cannot be returned? Look underneath.

2. The return statement in the finally block overrides return in the try block.
PublicClassFinallyTest2 {PublicStaticvoidMain (string[] args) {System.out.println (Test2 ());}PublicStaticIntTest2 () {int B = 20; try {System.out.println ("try block" ); return B + = 80;} catch (Exception e) {System.out.println ("Catch block") Span style= "color: #000000"); } finally {System.out.println ("finally block" if (b > 25 b); } return 200;} // return b;}}    

The operating result is:

Try blockfinally blockb>25, b = 100200  

This means that the return in the finally returns directly, regardless of whether there is a return statement in the try, there is a small detail to note, finally plus return, finally the outside of the return B becomes an unreachable statement, That is, you can never be executed, so you need to comment out or the compiler will error.

Here you may think: if there is no return statement in Finally, but modified the value of B, then return in the try is the modified value or the original value? Look underneath.

3. If no return statement overrides the return value in the finally statement, the original return value may change or be unchanged because of the modification in the finally.

Test Case 1:

PublicClassFINALLYTEST3 {PublicStaticvoidMain (string[] args) {System.out.println (Test3 ());}PublicStaticInt Test3 () {int b = 20; try {System.out.println ("try block" return B + = 80;} catch (Exception e) {System.out.println ("Catch block") Span style= "color: #000000"); } finally {System.out.println ("finally block" if (b > 25 b); } B = 150;} return 2000;}}       

The operating result is:

Try blockfinally blockb>25, b = 100100  

Test Case 2:

Import java.util.*;PublicClassfinallytest6{PublicStaticvoidMain (string[] args) {System.out.println (Getmap (). Get ("KEY"). ToString ()); }PublicStatic map<string, string>Getmap () {map<string, string> Map = new hashmap<string, string>(), Map.put ("KEY", "INIT"); C4>try {map.put ("KEY", "try"); return map;} Catch (Exception e) {map.put ("KEY", "catch");} finally {map.put ("KEY", "finally"); map = null;} return map;}}                

The operating result is:

FINALLY

Why is the B = 150 in the finally in test Case 1, and the map.put ("KEY", "finally") of the finally in test Case 2, which has no effect, and the map = null; But it didn't work? This is the question of whether Java is a value or a transmission address, specifically, please see a selection of 30 Java pen Questions answered, there is a detailed answer, in simple terms: there is only a value in Java is not transmitted, which is why map = null This sentence does not work. This also indicates that the return statement is a return statement in a try instead of a finally outside of return B; If you do not believe it, you can try it and return B; instead, return 294 will have no effect on the original result.

Here you may want to think: is not every time the return must be a try in the return statement? So finally the return B is not a bit of a function? Please look below.

4. The return statement in the try block will not be executed in the case of an exception, so it returns which one to see.
PublicClassFinallyTest4 {PublicStaticvoidMain (string[] args) {System.out.println (test4 ());}PublicStaticIntTest4 () {int B = 20; try {System.out.println ("try block" ); b = B/0; return B + = 80;} catch (Exception e) {b + = 15 ; System.out.println ("Catch block" finally {System.out.println ("finally block" if (b > 25 b); } B + = 50;} return 204;}}        

The operating result is:

Try blockcatch blockfinally blockb>25, b = 3585    
in this case, the return from the try is not executed until the 0 exception occurred before the return, but the catch statement that catches the exception and the final finally statement are executed, and both changes to B affect the final return value, then return b; It has a role to play. Of course if you change the return B to return 300 or something, the last one is 300, which is beyond doubt.

There may be another question here: What if there is a return statement in the catch? Of course, only in the case of exceptions can be executed, then the finally before the return? Look underneath.

5. When an exception occurs, the return execution in the catch is exactly the same as the execution of return in the try when no exception occurs.
PublicClassFINALLYTEST5 {PublicStaticvoidMain (string[] args) {System.out.println (TEST5 ());}PublicStaticIntTest5 () {int B = 20;Try; return B + = 80;} catch (Exception e) {System.out.println ("Catch block") Span style= "color: #000000"); return B + = 15;} finally {System.out.println ("finally block" if (b > 25 b); } B + = 50;} //return b;}}    

The results of the operation are as follows:

Try blockcatch blockfinally blockb>25, b = 3535    

After the exception has occurred, the return statement in the catch executes first, determines the return value, then executes the finally block, executes the catch and returns, and finally the change to B has no effect on the return value, the reason is the same as before. This means that the situation is exactly the same as the return statement in try.

Finally, the statement of a finally block is executed after the return statement in a try or catch is executed and the modified statement in finally may or may not affect the return value determined in the try or catch. If there is a return statement in Finally, the return statement in the try or catch is overwritten directly.

Is the Java finally statement executed before or after the return?

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.