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 {
//通常是关闭资源,比如关闭数据库,关闭打开文件
}
}
}