Left and right Java in the finally depth analysis statement block

Source: Internet
Author: User

First, let's ask you a question: will the finally declaration block run?

Many people think that the finally statement block is bound to run. It also includes some very experienced Java program apes. Unfortunately, not like many people imagine, for this question, of course, the answer is no, let's take a look at this sample after.

Inventory 1

public class Test {public      static void Main (string[] args) {          System.out.println ("Return value of Test ():" + Test ( ));      }         public static int Test () {          int i = 1;          if (i = = 1)          //return 0;         System.out.println ("the previous statement of Try Block");         i = i/0;           try {             System.out.println ("try block");               return i;         } finally {             System.out.println ("finally Block");}}}  


The running results for listing 1 are as follows:

The previous statement of Try block Exception in thread ' main ' java.lang.ArithmeticException:/by zero at Com.bj.charlie. Test.test (test.java:15) at Com.bj.charlie.Test.main (Test.java:6)


Other than that. Assuming that the gaze in front of the two statements in the previous example is removed, the result is:

return value of Test (): 0

In both of these cases. The finally statement block is not running, what is the problem?
There is only a case where the try statement block corresponding to finally should be run. The finally statement block will not run.
In both cases, either the TRY statement block is returned (return) or an exception is thrown, so the try corresponding finally statement block is not running.


Well, even if the try statement block corresponding to finally is running, will the finally statement block run?
Consider the following example (Listing 2).


Listing 2

public class Test {public      static void Main (string[] args) {          System.out.println ("Return value of Test ():" + Test ( ));      }         public static int Test () {          int i = 1;             try {             System.out.println ("try block");             System.exit (0);               return i;         } finally {             System.out.println ("finally Block");}}}     


The running results for listing 2 are as follows:

Try Blocktry block

The finally statement block is still not running, why?


Because we executed the System.exit (0) statement in the TRY statement block. Aborted execution of the Java virtual machine.

That's what someone said. This system.exit (0) method is essentially not called in a generic Java application.
Ok! No problem, we do not call System.exit (0) This method, then the finally statement block will certainly run?

The answer is still negative.

A thread is interrupted (interrupted) or terminated (killed) when it runs a try statement block or a catch statement block. The finally statement block that corresponds to it may not run.
The more extreme situation is that when the thread executes a try statement block or a catch statement block, the sudden crash or power outage, the finally statement block will certainly not be executed.


There may be some people think that the reasons for the crash, power outages are not related, we just to illustrate the problem.

Finally Statement Demo sample description

Let's look at a simple example (listing 3) below.

Listing 3.
public class Test {public     static void Main (string[] args) {         try {             System.out.println ("try block");               return;         } finally {             System.out.println ("finally Block");}}}    


The result of Listing 3 is:

Try block finally block

Listing 3 shows that the finally statement block runs before the return statement in the TRY statement block


Let's see, there's another example.


Listing 4.

public class Test {public    static void Main (string[] args) {        System.out.println ("Reture Value of Test ():" + Test ());    }     public static int Test () {        int i = 1;         try {            System.out.println ("try block");            i = 1/0;              return 1;        } catch (Exception e) {            System.out.println ("Exception block");             return 2;        } finally {            System.out.println ("finally Block");}}}    


The result of Listing 4 is:

Try Blockexception block finally block reture value of test (): 2

Listing 4 illustrates that the finally statement block runs before the return statement in the CATCH statement block.

From the above listing 3 and listing 4. We can see that

In fact, the finally statement block is run before the return statement in a try or catch.


It is more generally said that the finally statement block should be run before the control transfer statement, except for the return of the control transfer statement. There are also break and continue.
In addition, the throw statement belongs to the control transfer statement. Although return, throw, break, and continue are all control transfer statements, there is a difference between them.


The return and throw transfer control of the program to their callers (invoker), and the break and continue control is transferred within the current method.


Listing 5.

public class Test {public     static void Main (string[] args) {         System.out.println ("Return value of GetValue ():" + G Etvalue ());     }       public static int GetValue () {         try {             return 0;         } finally {             return 1;     }}}


The result of the operation in Listing 5:

return value of GetValue (): 1


Listing 6. 

  public class Test {public      static void Main (string[] args) {          System.out.println ("Return value of GetValue ():" + G Etvalue ());      }         public static int GetValue () {          int i = 1;             try {             return i;        } finally {             i++;}}     }  



The result of the operation in Listing 6:

return value of GetValue (): 1

Using the above analysis, we can conclude that:

A finally statement block is run before a return statement in a try or catch.



As a result, it is easy to understand that listing 5 runs at 1.



Because the return 1 in finally. Statement to return 0 in the try. Statement before it is run. Then the return 1 in finally.
After the statement runs. The control of the program is forwarded to its caller main () function, and the return value is 1.

So why is the return value of listing 6 not 2, but 1?

According to the analytic Logic of listing 5, the i++ in the finally;
The statement should be run before return I in the try?
The initial value of I is 1, then run i++; then 2. Run return I again. Isn't that supposed to be 2? How did it become 1?

Let's analyze the order of operation: it is divided into normal operation (no exception) and abnormal operation (with exception). Let's take a look at the normal running situation first. 1 What you see:


Figure 1. GetValue () function is working correctly

By, we can clearly see that before the finally statement block (Iinc 0, 1) is run, the GetValue () method saves its return value (1) to the location of the local surface scale 1. The command to complete this task is istore_1; then run the finally statement block (Iinc 0, 1). The finally statement block adds 1 to the value in the local variable table at position 0. becomes 2; After the finally statement block has finished running. Restores the value of 1 in the local table scale to the operand stack (iload_1), and finally runs the ireturn instruction to return the value (1) from the current operand stack to its caller (main). This is why listing 6 results in 1, not 2.

Let's take a look at the abnormal running situation. Would someone ask. You do not have a catch statement in Listing 6, where is the exception handling? I think that's a good question, in fact. Even if there is no catch statement. The Java compiler compiles a byte code that has the default exception handling. Do not forget that there may be exceptions that you do not need to catch, such as RuntimeException and Error, except for the exceptions that need to be caught.


Figure 2. GetValue () function abnormal operation condition

Listing 7.


  public class Test {public      static void Main (string[] args) {          System.out.println ("Return value of GetValue ():" + G Etvalue ());      }         @SuppressWarnings ("finally") public      static int getValue () {          int i = 1;            try {             i = 4;        } finally {             i++;             return i;}}     }


The result of the operation in Listing 7:

return value of GetValue (): 5


Listing 8.

public class Test {public     static void Main (string[] args) {          System.out.println ("Return value of GetValue ():" + G Etvalue ());      }         public static int GetValue () {          int i = 1;             try {             i = 4;         } finally {             i++;         }           return i;     }}



The result of the operation in Listing 8:


return value of GetValue (): 5


Let's look at a slightly more complicated sample – listing 9.


Listing 9.

public class Test {public      static void Main (string[] args) {          System.out.println (test ());      }         public static String test () {          try {              System.out.println ("try block");                return test1 ();         } finally {             System.out.println ("finally Block");         }     }       public static String Test1 () {         System.out.println ("return statement");           Return "after Return";}     }



Results from Listing 9:

Try block return statementfinally block after return


return test1 (); This statement is equivalent to:

String tmp = Test1 (); return TMP;

This item. It should be clear why the result is seen above the bar.

Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.

Left and right Java in the finally depth analysis statement block

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.