finally
常见疑惑代码片段
(1)下面代码中的 finally
块会执行吗?
try {
// do something
System.exit(1);
} finally{
System.out.println(“Print from finally”);
}
答案:不会。
(2)finally
会执行吗?
public static int test() {
try {
return 0;
} finally {
System.out.println("finally trumps return.");
}
}
答案:
finally trumps return.
0
(3)这个方法返回的值是 10 还是 12?
public static int getMonthsInYear() {
try {
return 10;
} finally {
return 12;
}
}
答案:12
(4)执行顺序
try{
int divideByZeroException = 5 / 0;
} catch (Exception e){
System.out.println("catch");
return; // also tried with break; in switch-case, got same output
} finally {
System.out.println("finally");
}
答案:
catch
finally
(5)赋值
public static void main(final String[] args) {
System.out.println(test());
}
public static int test() {
int i = 0;
try {
i = 2;
return i;
} finally {
i = 12;
System.out.println("finally trumps return.");
}
}
结果:
finally trumps return.
2
(6)执行顺序
public static void main(String[] args) {
System.out.println(Test.test());
}
public static int printX() {
System.out.println("X");
return 0;
}
public static int test() {
try {
return printX();
} finally {
System.out.println("finally trumps return... sort of");
}
}
结果:
X
finally trumps return... sort of
0
不会执行 finally 的情况
- 触发了
System.exit()
- 触发了
Runtime.getRuntime().halt(exitStatus)
- JVM Crash