异常传播是指从一个捕获块到另一个捕获块的异常流。以下是规则-
如果在受保护的代码中发生异常,则将该异常引发到列表中的第一个catch块。
如果抛出的异常的数据类型与ExceptionType1相匹配,它将在此处被捕获。
如果不是,则异常传递到第二个catch语句。
这一直持续到异常被捕获或陷入所有捕获为止。
在最终情况下,当前方法停止执行,并且异常被丢弃到调用堆栈中的前一个方法,此过程称为异常传播。
public class Tester {
public static void main(String args[]) {
int a,b;
try {
a = Integer.parseInt(args[0]);
b = Integer.parseInt(args[1]);
int c = a/b;
System.out.println(c);
} catch(ArrayIndexOutOfBoundsException ex) {
System.out.println("Please pass the args while running the program");
} catch(NumberFormatException e) {
System.out.println("String cannot be converted as integer");
} catch(ArithmeticException e1) {
System.out.println("Division by zero is impossible"); }finally {
System.out.println("The program is terminated");
}
}
}输出结果
Please pass the args while running the program The program is terminated