Java 中finally和return的执行顺序

前言

在 Java 的异常处理中,try、catch 和 finally 是按顺序执行的。

如果 try 中没有异常,则顺序为 try→finally;

如果 try 中有异常,则顺序为 try→catch→finally。

但是,当 try、catch、finally 中都加入 return 之后,return 和 finally 的执行顺序是咋样的?

注:finally 代码块是一定会被执行的。

我总结为以下几条:

  • 执行 try 代码块或 catch 代码块中的 return 语句之前,都会先执行 finally 语句;
  • 无论在 finally 代码块中是否修改返回值,返回值都不会改变,仍然是执行 finally 代码块之前的值;
  • finally 代码块中的 return 语句一定会执行,且是最终返回值。

测试

finally 代码块一定会在 try、catch 的return之前执行

public class Test1 {
    // 结果:先执行 finally 语句块中的代码,再 执行 try 中的 return
    public static int show() {
        try {
            return 1;
        } finally {
            System.out.println("执行finally模块");
        }
    }
    public static void main(String[] args) {
        System.out.println(show());
        // 控制台打印:
        // 执行finally模块
        // 1
    }
}

public class Test2 {
    // 结果:当 try 代码块或者 catch 代码块中有 return 时,finally 中的代码总会在return之前执行
    public static int show() {
        try {
            int a = 8 / 0;
            return 1;
        } catch (Exception e) {
            return 2;
        } finally {
            System.out.println("执行finally模块");
        }
    }
    public static void main(String[] args) {
        System.out.println(show());
        // 控制台打印:
        // 执行finally模块
        // 2
    }
}

finally 代码块修改返回值,但是,不会改变 try 或者 catch 最后返回的内容

public class Test4 {
    // 结果:在 finally 代码块中改变返回值并不会改变最后返回的内容。
    public static int show() {
        int result = 0;
        try {
            result = 1;
            return result;
        } finally {
            System.out.println("执行finally模块");
            result = 2;
        }
    }
    public static void main(String[] args) {
        System.out.println(show());
        // 控制台打印:
        // 执行finally模块
        // 1
    }
}

finally 代码块中的 return 语句 才是真正返回的结果

注:finally 代码块中最好不要包含 return 语句,否则程序会提前退出。

public class Test3 {
    // 结果:当 finally 有返回值时,会直接返回该值,不会去返回 try 代码块或者 catch 代码块中的返回值。
    public static int show() {
        try {
            int a = 8 / 0;
            return 1;
        } catch (Exception e) {
            return 2;
        } finally {
            System.out.println("执行finally模块");
            return 0;
        }
    }
    public static void main(String[] args) {
        System.out.println(show());
        // 控制台打印:
        // 执行finally模块
        // 0
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值