try,catch,finally结构中return的返回值

在这里插入图片描述
实验可能做的不太完善,还有好多情况没有实验,觉得意义也不大。简单总结一下运行的顺序。
首先执行try中的代码,如果有return,则保存住return的值后再执行finally的代码,如果finally中有return,那么则执行finally的return,如果finally中没有return,则执行完finally代码后,会再执行try中的return,返回的值是之前在try中保存的值。catch的原理与try是一样的。
最后一种情况,如果try中有错误跳转到了catch,则执行完finally会执行结构外的return,如果没有错误则执行完finally的代码,会返回try中保存的值。

public class Demo01 {
    	/*  本文主要讨论return在try结构中的返回值问题。
                分为四种情况进行测试
			        第一种情况,try中有return,并且有finally
				        结论:try中的return返回的值会在try中代码执行完毕后保存,先不返回,执行finally后再返回保存的值。
			        第二种情况,catch中有return
				        结论:与try中的执行顺序一致。
                    第三种情况,try,catch,finally中都有return
				        结论:执行finally中的return。
                    第四种情况,try以及结构后都有return
                        结论:执行try中的return*/


    public static void main(String[] args) {
        testDemo test = new testDemo();
        System.out.println("return: i="+test.test01());
        System.out.println("return: i="+test.test02());
        System.out.println("return: i="+test.test03());
        System.out.println("return: i="+test.test04());

    }

    public static class testDemo{

        /*第一种情况*/
        public int test01(){
            int i = 0;
            try{
                i++;
                return i;
            }finally {
                i++;
                System.out.println("finally:i="+i);
            }
        }

        /*第二种情况*/
        public int test02(){
            int i = 0;
            try{
                i+=1;
                i=3/0;
                return i;
            }catch (Exception e){
                i+=2;
                return i;
            }finally {
                i+=5;
                System.out.println("finally:i="+i);
            }
        }

        /*第三种情况*/
        public int test03(){
            int i = 0;
            try{
                i+=1;
                return i;
            }catch (Exception e){
                i+=2;
                return i;
            }finally {
                i+=5;
                System.out.println("finally:i="+i);
                return i;
            }
        }

        /*第四种情况*/
        public int test04(){
            int i = 0;
            try{
                i+=1;
                return i;
            }catch (Exception e){
                i+=2;

            }finally {
                i+=5;
                System.out.println("finally:i="+i);

            }
            return i+=100;
        }
    }

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值