当前位置 博文首页 > wanting1024的博客:Java基础(十二):try-catch-finally 中,

    wanting1024的博客:Java基础(十二):try-catch-finally 中,

    作者:[db:作者] 时间:2021-07-17 22:43

    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='王五'}

    ?

    cs