try-return-catch-finally
在finally
中执行返回值是非常不好的做法. 在一些语言中被直接禁止. 因为有很多副作用.
finally中直接使用return返回值
public static int finallyReturn(){
try{
System.out.println("about to return 1");
return 1;
} finally {
System.out.println("about to return 2");
return 2;
}
}
public static int finallyReturnWithException(){
int[] ints = new int[0];
try {
int n = ints[0];
return n;
} finally {
return 2;
}
}
// 异常完全被finally的return给吞了
public static int finallyReturnWithException2(){
try {
System.out.println("about to throw an exception");
throw new RuntimeException("doomed");
} finally {
return 2;
}
}
public static void finallyReturnWithException3(){
try{
throw new RuntimeException("something is wrong");
} finally {
return;
}
}
public static void main(String[] args) {
int result = finallyReturn();
System.out.println(result);
result = finallyReturnWithException();
System.out.println(result);
try {
result = finallyReturnWithException2();
} catch (Exception e){
// sadly, this won't happen.
System.out.println("caught the exception");
}
System.out.println(result);
try {
finallyReturnWithException3();
} catch (Exception e){
System.out.println("caught the exception");
}
}
输出:
about to return 1
about to return 2
2
2
about to throw an exception
2
可见finally
中return
的值覆盖了其他流程中的return
值. 更可怕的是finally
中使用return
, 将本来应该抛出的异常也吞了. 所以不应该在finally
中使用return
.