• 技术文章 >java >java基础

    java中finally不执行的分析

    小妮浅浅小妮浅浅2021-02-21 09:59:25原创2286

    本教程操作环境: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时格外注意。

    专题推荐:java中finally不执行
    品易云
    上一篇:java finally处理异常 下一篇:finalize在java中的清理

    相关文章推荐

    • java中try-catch的使用• java finally处理异常

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网