Java-finally

finally

1.finally是try-catch块中使用的关键字,无论try-catch是否有异常抛出都会执行finally块中的代码
2.不是代码中所有的finally都会执行,只有在执行到try-catch块时,这个try-catch块中的finally才会执行

1.Try catch 中有return finally还会执行吗

1、不管有没有catch到异常,finally块中代码都会执行;
2、当try和catch中有return时,finally仍然会执行;

2.try-catch-finally的执行顺序

public static void main(String[] args) {
    int res = tryTest();
    System.out.println(res);
}
private static int tryTest(){
        int res = 1;
        try{
            res = 1/0;
            System.out.println("There is try");
            return 8;
        }catch (Exception e){
            System.out.println("There is catch");
            //return 6;
        }finally {
            System.out.println("There is finally");
            //return 9;
        }
        return 10;
    }

Result 1:在try块中包含return

There is catch
There is finally
10

Result 2:在finall块中return,取消注释 return 9;注释return 10;

There is catch
There is finally
9

Result 3:在try、catch、finally中都有return

There is catch
There is finally
9

Result 4:不设置异常,res = 1/1,只注释return 10;

There is try
There is finally
9

Result 5:不设置异常,res = 1/1,注释return 10和9;

This is try
There is finally
8

结论:执行顺序 try->finally (->try)或catch->finally(->catch),如果finally中有return则不会执行try和catch中的return。
当try、catch中有return时,也会执行finally。

3.finally不执行的情况

1.不执行try catch,当然也就不会执行finally
2.在执行前出现其他异常,程序中断
3.在执行try或者catch中,有exit退出

try{
    res=1/1;
    System.out.println("This is try");
    System.exit(0);
    return 8;
}catch(Exception e){
    System.out.println("This is catch");
}finally{
    System.out.println("There is finally");
}

Result

This is try

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值