finally中return覆盖异常
public class FinallyReturnExample {
public static void main(String[] args) {
System.out.println(test());
}
public static int test() {
try {
int result = 10 / 0; // 这里将产生 ArithmeticException (除以零异常)
return result;
} catch (ArithmeticException e) {
System.out.println("Catch block: ArithmeticException caught");
throw e; // 在捕获后再次抛出异常
} finally {
System.out.println("Finally block: This will override the exception");
return 42; // 这里的 return 将覆盖 try 或 catch 中的异常
}
}
}
结果
本该捕获异常后中断程序,但是返回42,异常被吞了
Catch block: ArithmeticException caught
Finally block: This will override the exception
42