finally 中抛出异常会掩盖原异常吗
会。当 try 块或 catch 块中有未处理的异常正在向外传播时,如果 finally 块中也抛出了新的异常,这个新异常会直接覆盖(掩盖)掉原来的异常,导致调用者只能捕获到 finally 中的异常,而丢失了原始异常的堆栈信息。

public class ExceptionTest {
public static void main(String[] args) {
try {
methodThatThrows();
} catch (Exception e) {
System.out.println("Caught: " + e.getClass().getSimpleName());
}
}
public static void methodThatThrows() throws Exception {
try {
throw new RuntimeException("Original Error");
} finally {
throw new IllegalStateException("Finally Error");
}
}
}
运行上述代码,控制台输出为:
Caught: IllegalStateException
可以看到,原始的 RuntimeException 被完全吞没,只有 finally 中的 IllegalStateException 被捕获并打印。
如何避免 finally 掩盖原异常
要避免掩盖,必须在 finally 块中确保不会抛出异常,或者在抛出前保留原始异常。最安全的做法是在 finally 中使用 try-catch 包裹可能出错的代码,或者使用 Java 7 引入的 addSuppressed() 方法将新异常附加到原异常上。

public class SafeFinally {
public static void main(String[] args) {
try {
safeMethod();
} catch (Exception e) {
System.out.println("Caught: " + e.getClass().getSimpleName());
if (e.getSuppressed().length > 0) {
System.out.println("Suppressed: " + e.getSuppressed()[0].getClass().getSimpleName());
}
}
}
public static void safeMethod() throws Exception {
Exception original = null;
try {
throw new RuntimeException("Original Error");
} catch (Exception e) {
original = e;
throw e;
} finally {
if (original != null) {
try {
throw new IllegalStateException("Finally Error");
} catch (Exception suppressed) {
original.addSuppressed(suppressed);
}
}
}
}
}
运行上述代码,控制台输出为:
Caught: RuntimeException
Suppressed: IllegalStateException
这样既保留了原始异常的堆栈,又记录了 finally 中发生的错误。
finally 中不抛异常但修改返回值的情况
如果 finally 块中没有抛出异常,而是修改了局部变量或返回了不同的值,这种行为在某些情况下也会产生误导。特别是在 try-finally 结构中(没有 catch),如果 try 中有 return 语句,finally 中的 return 会覆盖 try 中的返回值。
public class ReturnOverride {
public static void main(String[] args) {
System.out.println(getValue());
}
public static int getValue() {
int x = 1;
try {
return x;
} finally {
x = 10;
// 注意:这里没有 return,所以不会覆盖返回值
// 但如果加上 return 100; 就会覆盖
}
}
}
运行上述代码,输出为 1。因为 return x; 在执行时已经确定了返回值是 1,finally 中对 x 的修改不影响已确定的返回值。但如果 finally 中有 return 100;,则输出将变为 100,且原始返回值被丢弃。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











