在 Java(以及很多类似语言,如 C#、JavaScript 等)中,finally 块的作用是:无论是否发生异常,都保证其中的代码一定会执行,通常用于资源清理和收尾工作。
finally 的基本作用try {
// 可能抛出异常的代码
} catch (Exception e) {
// 异常处理
} finally {
// 一定会执行的代码
}
核心特点:
try 中是否抛出异常catch 是否捕获异常try / catch 中是否有 return➡ finally 块几乎总是会执行
FileInputStream fis = null;
try {
fis = new FileInputStream("test.txt");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
lock.lock();
try {
// 业务处理
} finally {
lock.unlock(); // 保证锁一定释放
}
finally 与 return 的关系(易错点)finally 会在 return 前执行public static int test() {
try {
return 1;
} finally {
System.out.println("finally");
}
}
输出:
finally
返回值仍是 1
finally 中修改返回值(不推荐)public static int test() {
int i = 1;
try {
return i;
} finally {
i = 2;
}
}
返回值是 1(因为 return 时已经保存了值)
finally 中有 return(覆盖原 return)public static int test() {
try {
return 1;
} finally {
return 2;
}
}
✅ 返回 2(非常不推荐这样写)
finally 不执行的特殊情况 ⚠以下情况 finally 不会执行:
System.exit(0)finally vs try-with-resources(现代写法)Java 7+ 推荐方式:
try (FileInputStream fis = new FileInputStream("test.txt")) {
// 自动关闭资源
}
✅ 更简洁、更安全
finally的作用是:保证关键代码(如资源释放、状态恢复)无论如何都会执行。
如果你愿意,我也可以对比 finally 和 final、finalize 的区别。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。