深入理解Java中的异常链处理
在Java中,异常链处理是一种捕获和处理多个相关异常的方式。当一个异常被抛出,并且这个异常的父类也存在时,就会形成一个异常链。
以下是一个简单的示例:
public class ExceptionChainExample {
public void methodThatCanThrowException() {
try {
// 这里可能会抛出NumberFormatException或ArithmeticException
int divisionByZero = 10 / 0;
System.out.println("No exception thrown!");
} catch (NumberFormatException | ArithmeticException e) {
// 处理异常,这里捕获了两个可能的异常
System.out.println("Exception caught: " + e.getClass());
// 在这个层次,我们可以选择是否继续处理或抛出新的异常
if (e instanceof NumberFormatException) {
throw new IllegalArgumentException("Invalid number format.");
}
}
}
public static void main(String[] args) {
ExceptionChainExample example = new ExceptionChainExample();
try {
example.methodThatCanThrowException();
} catch (IllegalArgumentException e) {
System.out.println("Top-level exception caught: " + e.getMessage());
}
}
}
在这个例子中,methodThatCanThrowException()
方法可能抛出 NumberFormatException
或 ArithmeticException
。这些异常通过异常链传递给捕获它们的代码块。在 main()
方法中,我们模拟了这种异常链处理方式。
还没有评论,来说两句吧...