【四】finally执行顺序

天大地大妈咪最大 提交于 2020-01-10 14:38:42

1、d引用不变,finally块中修改了对象的内容,返回d引用

    public static Dog other() {
        Dog d = new Dog();
        try {
            d.setName("aaa");
            return d;
        } catch (Exception e) {
        } finally {
            d.setName("bbbb");
        }
        return d;
    }
bbbb

2、finally块中,d引用指向新对象,try中返回原对象的值

    public static Dog other() {
        Dog d = new Dog();
        try {
            d.setName("aaa");
            return d;
        } catch (Exception e) {
        } finally {
           d=new Dog();
           d.setName("bbbb");
        }
        return d;
    }
aaa

3、Integer 或String为final 类,值不可更改,finally 块中i重新赋值后,引用指向了2对象,不影响try中原对象1的返回

    public static Integer other2() {
        Integer i = 1;
        try {
            return i;
        } catch (Exception e) {
        } finally {
            i = 2;
        }
        return i;
    }
1

4、finally 块中i重新赋值后,引用指向了2对象,finally里的return语句则覆盖try中的return语句直接返回。

    public static Integer other2() {
        Integer i = 1;
        try {
            return i;
        } catch (Exception e) {
        } finally {
            i = 2;
            return i;
        }
    }
2
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!