栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java中finally不执行的分析

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java中finally不执行的分析

本教程操作环境: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;
        
        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不执行的分析,根据代码运行我们发现,finally在try语句未运行的情况也没有执行,这点需要我们在使用finally时格外注意。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/15236.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号