优于try和catch之前执行,无论是否异常都会执行
static int fun1(){
try{
return 1;
}finally {
System.out.println("finally");
}
}
// 输出 finally
// 1
public static void main(String[] args) {
System.out.println(fun1());
}
public static int fun1() {
int result = 0;
try {
result = 1;
return result; // 会将返回结果保存到临时变量 所以finally代码块修改了result也不影响最终返回值
} finally {
result = 2; // 即便在这里修改了 result 的值,最终返回的还是之前存储的 1
}
}
public static void main(String[] args) {
int a1 = 0;
try {
a1 = 1;
}catch (Exception e){
a1 = 2;
}finally {
a1 = 3;
}
System.out.println(a1); // 输出 3
}