Java中的TryCatch执行顺序

看到好多面试题都考TryCatch,就写一个博客记录一下

    public static void test()
    {   
        try {
            int x = 10/0;
            System.out.println("try");
        } catch (Exception e) {
            System.out.println("catch");
        }finally {
            System.out.println("finally");
        }
    }

当执行这段代码的时候会打印

catch
finally

说明捕捉到异常的时候会先执行catch 再执行finally
这个很容易理解
因为finally不论如何都会执行
可是当此代码的打印改为return的时候

    public static int test()
    {   
        try {
            int x = 10/0;
            return 1;
        } catch (Exception e) {
            return 2;
        }finally {
            return 3;
        }
    }

此时是不是应该返回2呢?答案是错误的,因为finally不论如何都会执行,所以finally会打断Catch的继续return,而执行finally中的return。
所以TryCatch有5条路径
当TryCatch中都没有return的时候
当无异常

try ->finally

当有异常

try(未出现异常的前半段) -> catch ->finally

当TryCatch中有return的时候
当无异常

try -> finally ->return(try)

当有异常

try(未出现异常的前半段) -> catch ->finally->return(catch)

当finally中有return中时
不论有没有异常,TryCatch中有没有return

try(catch)->return(finally)

我们可以看出当finally中有return的时候,相当于此代码肯定会返回该值。

补充

    public static int a(){
        try{
            System.err.println("try: "+2);
            return test1();
        }catch(Exception e){
            System.err.println("catch: "+3);
            return 3;
        }finally{
            System.err.println("finally: "+4);
            return 4;
        }
    }
    public static int test1(){
        System.err.println("test1: "+5);
        return 5;
    }

执行此代码并且打印其返回值的时候

System.out.println("main: "+a());

结果为

try: 2
test1: 5
finally: 4
main: 4

我们可以看出来此时并不是没有执行try中的return,虚拟机其实是已经为try中的return准备了值,即已经运行了test1函数给return 准备了5,但是并没有让他返回,只是让他准备返回,此时执行finally,但是因为finally中也有返回,所以finally中的return覆盖掉了try中return的5,所以main函数中接受到了4
图示
这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_38345606/article/details/80643901