finally语法:
try{
可能包含异常的代码
}catch(异常类 变量名){
异常处理代码
}…(多个catch)
finally{
后置处理代码
}
demo1
public static void main(String[] args) {
try {
test();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void test() throws Exception {
try {
throw new Exception("lalalala");
}catch (RuntimeException e){
e.printStackTrace();
}finally {
System.out.println("finally");
}
}
输出:
finally
java.lang.Exception: lalalala
at helloworld.exception.FinallyTeach.test(FinallyTeach.java:15)
at helloworld.exception.FinallyTeach.main(FinallyTeach.java:7)
结论:
异常如果没有被捕获,会执行finally的代码
demo2
public static void main(String[] args) {
try {
test2();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void test2() throws Exception {
try {
throw new RuntimeException("abcd");
}catch (RuntimeException e){
e.printStackTrace();
}finally {
System.out.println("finally");
}
}
输出:
finally
java.lang.RuntimeException: abcd
at helloworld.exception.FinallyTeach.test2(FinallyTeach.java:25)
at helloworld.exception.FinallyTeach.main(FinallyTeach.java:7)
结论: 如果异常被捕获,依然会执行finally里的代码
1.无论异常是否被捕获,finally的代码一定会被执行。
2.finally里适合存放释放资源、后续处理的代码