Java Exception 之 try catch finally

当在捕获Exception时,如果有finally块,且在finally中有return 语句,程序的运行flow该会是怎样的呢?我们直接写给例子来演示,

再总结分析。

package test;

/**
 * Created by xieguojun on 14-12-26.
 */
public class ExceptionDemo {
    public static void main(String[] args){
        int res = test();
        System.out.print(res);
    }

    public static int test(){
        try{
            System.out.print("a");
            try{
                promblem();
                return 1;
            }
            finally {
                System.out.print("g");
                return 2;
                //throw new RuntimeException();
            }

        }catch (RuntimeException re){
            System.out.print("d");
            return 3;
        }catch (Exception e){
            System.out.print("e");
        }
        finally {
            System.out.print("f");
            return 4;
        }
    }

    private static void promblem() {
        throw new RuntimeException();
    }
}
程序会打印出agf4

分析:

1.当java方法中的代码执行到return时,会在return执行之前检查该代码块是否被包裹在finally块中,如果有的话,则先执行finally块(块中没有return),如果该finally块的外层还有finally块,则继续跳到外层的finally块中执行(块中没有return),以此类推,最后返回到try块中执行return 语句。
2.如果finally块中也有return语句,则执行finally块中的return语句,如果该finally块被包裹在另一个finally块中,则跳到上层finally块,执行上层finally块中的return语句。上述例子就是最终返回的最外层的finally块的return语句,结果为4.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值