【发布时间】:2020-01-01 13:38:43
【问题描述】:
在下面的代码中,我试图打印多个 catch 语句,但我只得到一个。据我了解,订单是优先的,即将打印第一个匹配的 catch 语句。但我想打印两个相关的声明。有什么办法吗?
class Example2{
public static void main(String args[]){
try{
int a[]=new int[7];
a[10]=30/0;
System.out.println("First print statement in try block");
}
catch(ArithmeticException e){
System.out.println("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e){
System.out.println("Warning: Some Other exception");
}
System.out.println("Out of try-catch block...");
}
}
我想要打印越界和算术语句。有什么办法吗?
【问题讨论】:
-
我不这么认为。您将只能获得其中之一。
-
代码将在
ArithmeticException或ArrayIndexOutOfBoundsException上失败,不会在两者上都失败。 -
这样想:如果“发生了一些异常”,为什么代码会继续执行(并且可能会得到另一个“异常”)?它会立即尝试处理第一个异常。