Java基础(十二):try-catch-finally 中,如果 catch 中 return 了,finally 还会执行吗?

catch中有return,finally中没有 

public class FinallyTest {
    public static void main(String[] args) {
        System.out.println(test());
    }

    public static int test() {
        int a = 5;
        try {
            System.out.println(a / 0);
            a = 10;
        } catch (ArithmeticException e) {
            return a = 20;//程序执行到这时,a=20已经执行完,准备好返回结果了,发现有finally,则在去执行finally
        } finally {
            a = 30;
        }
        return a;
    }
}

//输出结果
20

catch中有return,finally中也有 

public class FinallyTest {
    public static void main(String[] args) {
        System.out.println(test());
    }

    public static int test() {
        int a = 5;
        try {
            System.out.println(a / 0);
            a = 10;
        } catch (ArithmeticException e) {
            return a = 20;//程序执行到这时,a=20已经执行完,准备好返回结果了,发现有finally,则在去执行finally
        } finally {
            return a = 30;//由于一个方法只能有一个return,执行到这,就直接返回了
        }
    }
}

//输出结果
30

 如果catch、finally块中,处理的是对象的属性,则都是以finally为准

public class FinallyTest {
    public static void main(String[] args) {
        System.out.println(getName());
    }

    public static User getName() {
        User user = null;
        try {
            user = new User(null);
        } catch (Exception e) {
            try {
                user = new User(null);
            } catch (Exception ex) {
                try {
                    return user = new User("李四");
                } catch (Exception exc) {
                    exc.printStackTrace();
                }
            }
        } finally {
            user.setName("王五");
            return user;
        }
    }
}

class User {
    private String name;

    public User(String name) throws Exception {
        if (name == null) {
            throw new Exception();
        }
        this.name = name;
    }

    //此处省略get/set/toString方法
}

//输出结果
User{name='王五'}

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值