try..catch..finally结构 与 return问题

java中finally什么时候执行?return语句与其执行相关顺序是怎样的?

package cn.gestwr.test;

/***
 *@author gestwr
 *@data 2022/8/12
 */
public class TestFinally {
    public static void main(String[] args) {
        System.out.println("Hello World!");

        System.out.println("This is " + testFinally());
    }

    static int testFinally() {
        int a = 0;

        try {
            System.out.println("This is try");
            return a;
            //return a / 0;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("This is catch");

            //throw e;
            //a = 1;
            //return a;   //如果没有throw 或者 finall块里没有return,则返回该处的值
        } finally {
            System.out.println("This is finally");
            //a = 2;
            //return a;  //掩盖所有return的值
        }

        //前面如果有throw-》finally执行完后,后面的语句不会执行
         a = 3; //如果try块一切正常,finally没有return,最终返回值是try块的0 而不是这里的3
         return a;
    }
}

注:
try块或者catch块中有 System.exit(0); 语句,则程序到此直接退出,不执行finally块

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值