代码示例
public class ExceptionChainingExample {
public static void main(String[] args) {
try {
method1();
} catch (OuterException e) {
e.printStackTrace();
}
}
private static void method1() throws OuterException {
try {
method2();
} catch (InnerException e) {
// 将 InnerException 作为 OuterException 的原因构建异常链
throw new OuterException("发生外层异常", e);
}
}
private static void method2() throws InnerException {
throw new InnerException("发生内层异常");
}
}
class OuterException extends Exception {
public OuterException(String message, Throwable cause) {
super(message, cause);
}
}
class InnerException extends Exception {
public InnerException(String message) {
super(message);
}
}
异常链的好处
- 保留完整的异常信息:通过异常链,可以在抛出高层异常时,将底层异常作为原因包含进来,使得开发者在捕获高层异常时,不仅能知道高层异常的信息,还能追溯到引发该异常的底层原因,方便定位问题根源。
- 更好的错误处理:在大型项目中,不同层次的代码可能会捕获和处理不同类型的异常。异常链可以让上层代码在处理异常时,根据底层异常的类型和信息,做出更精准、更合适的处理决策。
- 提高代码的可维护性:异常链使得异常传递和处理过程更加清晰,当出现问题时,开发者能够沿着异常链快速定位到问题发生的具体位置,有助于快速修复代码中的错误,提高代码的可维护性。