首页 > 其他 > 详细

try {}里有一个return语句,那么紧跟在这个try后的finally {}里的code会不会被执行,什么时候被执行,在return前还是后?

时间:2020-07-16 16:09:02      阅读:31      评论:0      收藏:0      [点我收藏+]

一, 

package demo;

public class tryDemo {
    private static int see(){
        int s = 0;
        try{
            s +=2;
            System.out.println("执行完try");
            return s;
        }catch(Exception e){
            return s+1;
        }finally{
            System.out.println("执行完finally");
            
        }
    }
    public static void main(String[] args) {
        int a = see();
        System.out.println("a : "+ a );
    }
}

运行结果:

执行完try
执行完finally
a : 2

说明,如果 try当中有return 的话, 先执行完return中的语句,在执行finally中的语句,最后 返回 try 中的 return。

二,如果 finally当中也有 return呢 ?

package demo;

public class tryDemo {
    private static int see(){
        int s = 0;
        try{
            s +=2;
            System.out.println("执行完try");
            return s;
        }catch(Exception e){
            return s+1;
        }finally{
            System.out.println("执行完finally");
            return s+3;
            
        }
    }
    public static void main(String[] args) {
        int a = see();
        System.out.println("a : "+ a );
    }
}

输出结果:

执行完try
执行完finally
a : 5

说明: 这种情况下,不执行 try当中的 return ,最后返回的是 finally 中的值 。

三 ,

如果 try当中有 return s,

finally没有 return, 但在 finally 中 有 对 s 的操作,那么 try 当中的 return  s 是 更改后的 s 吗?

package demo;

public class tryDemo {
    private static int see(){
        int s = 0;
        try{
            s +=2;
            System.out.println("执行完try");
            return s;
        }catch(Exception e){
            return s+1;
        }finally{
            System.out.println("执行完finally");
            s +=1;
            //s=5;
            
        }
    }
    public static void main(String[] args) {
        int a = see();
        System.out.println("a : "+ a );
    }
}

输出结果:

执行完try
执行完finally
a : 2

说明, finally当中的 对 s 的修改 并不对 try当中的 return 值产生影响。

 

try {}里有一个return语句,那么紧跟在这个try后的finally {}里的code会不会被执行,什么时候被执行,在return前还是后?

原文:https://www.cnblogs.com/william-dai/p/13322071.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!