In the try{}catch{}finally{} block, you know that the finally child block is sure to execute. There are, of course, individual cases where the finally child block is not executed when a forced exit System.exti (int) appears in the try{} or catch{} block. This situation is not within the scope of today's discussion.
Look at the code more intuitively:
Java code
- Package practice;
- Public class Finallyrun {
- private int a = 0;
- public int getInt () {
- try {
- A = 1;
- return A;
- } finally {
- A = 2;
- return A;
- }
- }
- public static void Main (string[] args) {
- Finallyrun f = new Finallyrun ();
- int tmp = F.getint ();
- System.out.println ("f.getint () =" + tmp);
- System.out.println ("F.A =" + F.A);
- }
- }
I a=1 out a break, one-step trace found: Although the try contains a return, and the return statement in the try executes, the program jumps to finally, continues to run, and then returns the Exit Getint () method. The results are as follows:
Java code
- F.getint () = 1
- F.A = 2
As you can see from the results, the GETINT () method returns 1 of the value, while the value of variable A is 2. Cancel the comment in the code and run the program with the following results:
Java code
- F.getint () = 2
- F.A = 2
Both the value of the variable A and the method return value are 2.
The process is relatively simple. After the return execution in try{}, the return stream is taken to the finally child block, although the value of variable A is modified in finally, but does not affect the data in the return stream, and if finally there is a return statement, Then the return stream in the finally child block overwrites the return stream in the previous try{} and exits from the method.
If there is any mistake, please correct me.
Execution of finally blocks in Java