在 Java 中,finally 不是必须写的。
try 可以单独存在(但不推荐,通常要有 catch 或 finally)catch 可选finally 可选try 后面至少要跟 catch 或 finally 中的一个✅ 合法示例:
try {
int a = 1 / 0;
} catch (Exception e) {
e.printStackTrace();
}
✅ 合法示例(没有 catch,只有 finally):
try {
int a = 1 / 0;
} finally {
System.out.println("执行finally");
}
❌ 不合法示例(只有 try):
try {
int a = 1 / 0;
}
finally 什么时候用?finally 通常用于 不管是否发生异常,都必须执行的代码,例如:
FileInputStream fis = null;
try {
fis = new FileInputStream("a.txt");
} finally {
if (fis != null) fis.close();
}
从 Java 7 开始,推荐使用 try-with-resources,可以自动关闭资源,不需要手写 finally:
try (FileInputStream fis = new FileInputStream("a.txt")) {
// 使用资源
} catch (IOException e) {
e.printStackTrace();
}
finally 不是 100% 一定执行,以下情况不会执行:
System.exit()✅ finally 不是必须写的
✅ try 后面至少要有 catch 或 finally
✅ 资源管理推荐用 try-with-resources
如果你愿意,我也可以帮你对比 return / throw 时 finally 的执行顺序。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。