温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java Finally最终何时才执行

发布时间:2026-11-10 06:05:40 来源:亿速云 阅读:95 作者:小樊 栏目:编程语言

在 Java 中,finally 块通常用于保证一段代码“无论如何都会执行”,但“最终何时执行”取决于具体场景。下面系统地说明。


一、正常情况下的执行时机

1️⃣ try-catch-finally 正常流程

try {
    // 可能抛异常
} catch (Exception e) {
    // 处理异常
} finally {
    // 一定执行
}

执行顺序:

  1. 执行 try
  2. 若有异常 → 执行 catch
  3. 无论是否异常,最后执行 finally

✅ 即使 try 或 catch 中有 return,finally 也会先执行。


二、finally 在 return 之前的执行时机(重点)

示例 1:try 中 return

public static int test() {
    try {
        return 1;
    } finally {
        System.out.println("finally");
    }
}

执行顺序:

  1. 计算 return 1
  2. 暂停 return
  3. 执行 finally
  4. 真正返回

输出:

finally

示例 2:finally 中修改返回值(坑点)

public static int test() {
    int x = 1;
    try {
        return x;
    } finally {
        x = 2;
    }
}

✅ 返回值是 1,不是 2
原因:return x 已经把值“拷贝”了


三、finally 不执行的情况(重要)

以下情况 finally 不会执行:

❌ 1. 调用 System.exit()

try {
    System.exit(0);
} finally {
    System.out.println("不会执行");
}

❌ 2. JVM 崩溃 / 断电 / 系统kill

  • 死机
  • kill -9
  • 硬件故障

❌ 3. 守护线程被强制结束

Thread t = new Thread(() -> {
    try {
        while (true);
    } finally {
        System.out.println("可能不会执行");
    }
});
t.setDaemon(true);
t.start();

四、finally 与异常的关系

finally 本身抛异常

try {
    throw new RuntimeException("try");
} finally {
    throw new RuntimeException("finally");
}

✅ finally 的异常会覆盖 try 的异常


五、try-with-resources 中的 finally

try (InputStream in = new FileInputStream("a.txt")) {
    // 自动关闭
} finally {
    // 仍会执行
}

✅ finally 在资源关闭之后执行


六、总结一句话版

finally 在方法返回前、异常抛出前执行,除非 JVM 退出或线程被强制终止。

如果你愿意,我也可以:

  • 用 字节码层面解释
  • 对比 C++ / Python
  • 讲 面试常问 finally 题
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手