Java异常处理:典型链式异常捕获案例
在Java中,异常处理是通过try-catch-finally语句来实现的。链式异常捕获是指在一个catch块不能处理的异常时,将这个异常传递给下一个catch块。
下面是一个典型的链式异常捕获案例:
public class ChainExceptionHandling {
public void handleException() {
try {
// 产生一个异常
int divisionByZero = 1 / 0;
System.out.println("Divide by zero performed successfully.");
} catch (ArithmeticException e) {
// 这里捕获的是除以零的异常
System.out.println(" caught an Exception : " + e.getMessage());
// 尝试将异常传递给下一个catch块
handleCustomException(e);
} catch (Exception e) {
// 这个catch块会捕获所有未被前面catch块处理的异常
System.out.println(" caught an Exception : " + e.getMessage());
throw new RuntimeException("Cannot handle exception", e);
}
}
// 自定义异常处理方法,用于将特定类型的异常传递给下一个catch块
private void handleCustomException(Exception e) {
if (e instanceof NullPointerException) {
System.out.println(" handling a custom Exception : " + e.getMessage());
throw new RuntimeException("Cannot handle null pointer exception", e);
} else {
// 如果不是我们自定义的异常类型,就直接打印异常信息并抛出运行时异常
System.out.println(" handling a custom Exception : " + e.getMessage());
throw new RuntimeException("Cannot handle custom exception", e);
}
}
public static void main(String[] args) {
ChainExceptionHandling handler = new ChainExceptionHandling();
handler.handleException();
}
}
在这个例子中,我们首先生成一个除以零的异常(ArithmeticException),然后使用链式异常捕获,将这个异常传递给下一个catch块。最后在main方法中调用处理函数并打印结果。
还没有评论,来说两句吧...