It is a specific analysis of the try return finally statement

I believe that if you look carefully, every Java book has covered it. "Assume the return statement is used to exit from the try block. Before the method returns, the contents of the finally clause will be executed. If the finally clause also has a return statement, the return value will overwrite the original return value."
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static void main(String[] args) {
         int k = f_test();
         System.out.println(k);
     }
     
     public static int f_test(){
         int a =  0 ;
         try {
             a =  1 ;
             return a;
         }
         finally {
             System.out.println( "It is in final chunk." );
             a =  2 ;
             return a;
         }
     }
output: 
It is in final chunk.
2
public static int f_test(){
int a = 0;
try{
a = 1;
return a;
}
finally{
System.out.println("It is in final chunk.");
a = 2;
// return a;
}
}
If you comment out return a;, it will output
It is in final chunk.
1        

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326500946&siteId=291194637