Java中的异常传播
从堆栈顶部引发异常时,Java中会发生异常传播。如果未捕获到该异常,则该异常会丢弃前面方法的调用堆栈。如果没有被发现,它将进一步下降到以前的方法。继续进行直到该方法到达调用堆栈的底部或陷入两者之间的某个位置为止。
示例
让我们看一个示例,该示例说明Java中的异常传播-
public class Example {
void method1() // generates an exception {
int arr[] = {10,20,30};
System.out.println(arr[7]);
}
void method2() // doesn't catch the exception {
method1();
}
// method1 drops down the call stack
void method3() // method3 catches the exception {
try {
method2();
} catch(ArrayIndexOutOfBoundsException ae) {
System.out.println("Exception is caught");
}
}
public static void main(String args[]) {
Example obj = new Example();
obj.method3();
}
}输出结果
输出如下-
Exception is caught