try/catch/finally的簡單實踐

記錄一下try/catch/finally的執行,總有點混淆:測試

  1. 先測試基本類型
private static int test1(){
        int i = 1;
        try {
            return i;//①第一步執行
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            i = 0;//②第二步執行,執行完後再執行①
        }
        return i;//不執行
    }
    private static int test2(){
        int i = 1;
        try {
            return i;//①第一步執行
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            i = 0;//②第二步執行
            return i;//③第三步執行
        }

    }
  1. 測試引用類型
private static User test3(){
        User user = new User("張三");
        try {
            return user;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            user = new User("李四");
        }
        return user;
    }
    private static User test4(){
        User user = new User("張三");
        try {
            return user;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            user.setName("李四");
        }
        return user;
    }
class User{
    private String name;

    public User(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}
public static void main(String[] args) {
        System.out.println("test1返回:"+test1());//結果:1
        System.out.println("test2返回:"+test2());//結果:0
        System.out.println("test3返回:"+test3());//結果:User{name='張三'}
        System.out.println("test4返回:"+test4());//結果:User{name='李四'}
 }

總結:this

1. 不管try執行什麼,finally都會執行; 

2. 若是在try中執行了return語句,在執行finally以前會將return的結果保存下來,即便在finally中從新賦        
    值,仍然以try中保存的值 返回,但若是是引用類型,在finally中修改了原來對象中的值,以修改後的值
    返回;

3.若是try和finally中都有return,直接返回finally中的值code

相關文章
相關標籤/搜索