在 Java 中,finally 块“通常”一定会执行,但不是 100% 绝对会执行。下面分情况说明。
只要程序进入了 try 块,并且JVM 没有被强制终止,finally 就会执行。
try {
int a = 1 / 0;
} catch (Exception e) {
System.out.println("catch");
} finally {
System.out.println("finally");
}
输出:
catch
finally
public static int test() {
try {
return 1;
} finally {
System.out.println("finally");
}
}
输出:
finally
(然后返回 1)
System.exit()try {
System.exit(0);
} finally {
System.out.println("finally");
}
❌ finally 不会执行
❌ finally 不会执行
System.out.println("before");
System.exit(0);
try {
// 不会进来
} finally {
System.out.println("finally");
}
❌ finally 不会执行
public static int test() {
try {
return 1;
} finally {
System.out.println("finally");
}
}
执行顺序:
Connection conn = null;
try {
conn = getConnection();
} finally {
if (conn != null) conn.close();
}
⚠️ 现在更推荐
try-with-resources
finally 在“正常 JVM 运行且进入 try 块”时一定会执行,但不是绝对执行(如 System.exit / JVM 崩溃不会执行)。
如果你愿意,我也可以帮你画执行流程图或者用面试题角度来讲。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。