当前位置:网站首页>Example of try catch finally execution sequence

Example of try catch finally execution sequence

2022-06-13 03:52:00 Brother Yu...

public class TryDemo {
    
    public static void main(String[] args) {
    
        System.out.println(test());
    }
    public static int test() {
    
        try {
    
            return 1;
        } catch (Exception e) {
    
            return 2;
        } finally {
    
            System.out.print("3");
        }
    }
}

Program first enters try in , return 1, Then go back to continue finally Print 3, The function is finished , take 1 Return to the main function , Then the main function outputs 1

 public static void main(String[] args) {
    
        System.out.println(test1());
    }
    public static int test1() {
    
        try {
    
            return 2;
        } finally {
    
            return 3; 
        }
    }

In principle, it will return first 2, Then enter finally Back in 3, But a program can only have one return value ,finally The block is the last to execute , So the return is 3, The end result is 3

 public static void main(String[] args) {
    
        System.out.println(test1());
    }
    public static int test1() {
    
        int i = 0;
        try {
    
            i = 2;
            return i;
        } finally {
    
            i = 3;
        }
    }

Get into try Give first i The assignment is 2, Then return it to , Next close finally Block medium i Set to 3,finally The code in is just for i Assigned value , Does not change the return value i Value , So the return is 2, The end result is i

Conclusion :

1、 No matter if there is any abnormality ,finally All the code in the block will execute ;
2、 When try and catch There is return when ,finally Still execute ;
3、finally Is in return The following expression is evaluated ( The calculated value is not returned , Instead, save the value you want to return , No matter finally What about the code in , The value returned will not change , It's still the value that we saved before ), So the return value of the function is at finally Determined before execution ;
4、finally It is best not to include return, Otherwise the program will exit early , The return value is not try or catch The return value saved in

原网站

版权声明
本文为[Brother Yu...]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/164/202206130338592759.html