Java中的 finally 和 return 的执行顺序

    以下过程得出唯一解,那就是,无论 try 还是 catch 中有 return 语句,无论代码有没有捕捉到异常,finally 代码块最终肯定会执行的,放心好了。

try中有 return 语句时:

运行结果:



catch 中有 return 且代码捕捉到异常时:


运行结果:



附上代码:

public class Finally {

    public static void main(String[] args) {

//        try{
//            return;
//        }catch(Exception e){
//            e.printStackTrace();
//        }finally {
//            System.out.println("finally语句执行-----1");
//        }

        try{
            int i = 1/0;
        }catch(ArithmeticException e){
            e.printStackTrace();
            return;
        }finally {
            System.out.println("finally语句执行-----2");
        }
    }
}

猜你喜欢

转载自blog.csdn.net/m0_37738114/article/details/80759019
今日推荐