品易云推流 关闭
文章详情页
文章 > java基础 > java中finally不执行的分析

java中finally不执行的分析

头像

小妮浅浅

2021-02-21 09:59:253175浏览 · 0收藏 · 0评论

本教程操作环境:windows7系统、java10版,DELL G3电脑。

1. try 语句块之前返回(return)或者抛出异常,finally不会被执行

package com.zwwhnly.springbootaction;
 
public class FinallyTest {
    public static void main(String[] args) {
        System.out.println("return value of test():" + test());
    }
 
    public static int test() {
        int i = 1;
        /*if (i == 1) {
            return 0;
        }*/
        System.out.println("the previous statement of try block");
        i = i / 0;
        try {
            System.out.println("try block");
            return i;
        } finally {
            System.out.println("finally block");
        }
    }
}

只有与 finally 相对应的 try 语句块得到执行的情况下,finally 语句块才会执行。

2.有异常,finally 中的 return会导致提前返回

public static String test() {
        try {
            System.out.println("try");
            throw new Exception();
        } catch(Exception e) {
            System.out.println("catch");
            return "return in catch";
        } finally {
            System.out.println("finally");
            return "return in finally";
        }
    }

调用 test() 的结果:

try
catch
finally
return in finally

finally 语句块在 try 语句块中的 return 语句之前执行。

以上就是关于java中finally不执行的分析,根据代码运行我们发现,finallytry语句未运行的情况也没有执行,这点需要我们在使用finally时格外注意。

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图