finally中的代码块在异常处理(catch块)以后执行
finally块 通常是关闭资源,比如关闭数据库,关闭打开文件
package test;
public class Test {
public static void main(String[] args) {
try {
int x = 3/0;
}catch(Exception e) {
e.printStackTrace();
}finally {
//通常是关闭资源,比如关闭数据库,关闭打开文件
}
}
}
以下情况,finally块不执行
package test;
public class Test {
public static void main(String[] args) {
try {
int x = 3/0;
}catch(Exception e) {
e.printStackTrace();
return; //注意,处理完异常停止,不执行finally
}finally {
//通常是关闭资源,比如关闭数据库,关闭打开文件
}
}
}
本文详细介绍了Java中finally块的作用及执行机制,强调了其在资源管理和异常处理中的重要性,并给出了具体的代码示例。
1868

被折叠的 条评论
为什么被折叠?



