Java的try/catch/finally中使用return详解

finally是无论如何都要执行的,除非在try/catch的语句块中使用的System.exit()

为了弄清楚Java中try/catch/finally中使用return语句的跳转,使用下面示例:

1. 首先在try中使用returnfinally中不使用return
public class App {
    public static void main(String[] args) throws Exception {
        App app = new App();
        String res = app.test();
        System.out.println(res);
    }

    public String test() {
        try {
            System.out.println("正在执行  try");
            return new String("返回  try");
        } catch (Throwable throwable) {
            System.out.println("异常");
            return new String("catch");
        } finally {
            System.out.println("正在执行  finally");
            // return new String("返回  finally");
        }
    }
}
执行结果

在这里插入图片描述
由此可见执行顺序:try中语句——>finally中语句——>try中return语句

2. 在try中使用returnfinally中也使用return
public class App {
    public static void main(String[] args) throws Exception {
        App app = new App();
        String res = app.test();
        System.out.println(res);
    }

    public String test() {
        try {
            System.out.println("正在执行  try");
            return new String("返回  try");
        } catch (Throwable throwable) {
            System.out.println("异常");
            return new String("catch");
        } finally {
            System.out.println("正在执行  finally");
            return new String("返回  finally");
        }
    }
}

执行结果

在这里插入图片描述
执行顺序:try中语句——>finally中语句——>finally中的return

3. 在catch中使用return
public class App {
    public static void main(String[] args) throws Exception {
        App app = new App();
        String res = app.test();
        System.out.println(res);
    }

    public String test() {
        try {
            System.out.println("正在执行  try");
            throw new Throwable("Some error");
        } catch (Throwable throwable) {
            System.out.println("异常");
            return new String("catch");
        } finally {
            System.out.println("正在执行  finally");
            return new String("返回  finally");
        }
    }
}

执行顺序和前面类似:try中语句——>catch中语句——>finally中语句——>finally中return

综上所述

在执行完trycatch语句中后,都会执行finally中的语句,此时,如果finally中有return就直接从这里跳出。如果没有的话,就从try或者catch中的return中返回。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值