【深入Java基础】catch和finally中的return

catch和finally中的return

Q1:catch中出现return后finally还会执行嘛?

有以下代码:

    File file = new File("C:\\Users\\Administrator\\Desktop\\aa.txt");
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("异常");
            return;
        }finally {
            System.out.println("finally");
        }

我们读取一个不存在的文件;并在catch中添加return语句。输出如下:

    异常
    java.io.FileNotFoundException: C:\Users\Administrator\Desktop\aa.txt (系统找不到指定的文件。)
    finally

说明即使catch中有return语句,finally还是会执行。

Q2:return和finally哪个先执行的?

按照官方文档说明:return是在finally执行之后执行的。也就是先执行finally里的内容在return。

这有一个例子:

    public static void main(String[] args) {
        System.out.println(a(0));
    }
    public static  int a(int i){
        try{
            throw new Exception("异常");
        }catch (Exception e){
            return i;
        }finally {
            ++i;
        }
    }

i赋初值为0,捕获到异常后进入catch,catch里有return,但是后边还有finally,先执行finally里的,对i+1=1,然后return。那return的是1?事实上不是1,而是0.为何?

这是返回时的i值:

可以清楚的看到i=1;但是返回的确是0?那说明此i非彼i,就是返回的i不是这个i。

因为这里是值传递,在执行return前,保留了一个i的副本,值为0,然后再去执行finally,finall完后,到return的时候,返回的并不是当前的i,而是保留的那个副本,也就是0.所以返回结果是0.

当然对于引用传递那么return和finally两处都是引用的同一个对象,所以返回的是finally执行之后的值。

    public static void main(String[] args) {
        System.out.println(a(new A()).num);
    }
    public static A a(A a){
        try{
            throw new Exception("异常");
        }catch (Exception e){
            return a;
        }finally {
            ++a.num;
        }
    }

    class A{
    public int num;
    }

这里返回的一个对象a,所以输出结果为1.

Q3:当catch和finally中都有return时返回的是哪个?

有如下代码:

    public static void main(String[] args) {
        System.out.println(a(0));
    }
    public static  int a(int i){
        try{
            throw new Exception("异常");
        }catch (Exception e){
            return i;
        }finally {
            ++i;
            return i;
        }
    }

输出结果为:1

这个很容易理解,因为是先执行finally里的,当finally里return就直接返回了,并不会再去执行catch里的return。

总结:

1. 在catch中有return的情况下,finally中的内容还是会执行,并且是先执行finally再return。


2. 需要注意的是,如果返回的是一个基本数据类型,则finally中的内容对返回的值没有影响。因为返回的是finally执行之前生成的一个副本。


3. 当catch和finally都有return时,return的是finally的值。

posted @ 2018-02-20 18:18  SEC.VIP_网络安全服务  阅读(174)  评论(0编辑  收藏  举报