Java 例外情况中的优先权
所以我正在准备一个涉及异常处理的期中考试。我一辈子都搞不懂我写的这个多重捕获的输出Java 例外情况中的优先权,java,exception,Java,Exception,所以我正在准备一个涉及异常处理的期中考试。我一辈子都搞不懂我写的这个多重捕获的输出 System.out.println("first try"); try{ int[] array = new int[24]; array[array.length] = 30/0 ; }catch (ArithmeticException e){ System.out.println("divide by zero
System.out.println("first try");
try{
int[] array = new int[24];
array[array.length] = 30/0 ;
}catch (ArithmeticException e){
System.out.println("divide by zero");
}
catch (ArrayIndexOutOfBoundsException e){
System.out.println("array size problem");
}
catch (Exception e){
System.out.println("shouldnt be called");
}
System.out.println("second try");
try{
int[] array = new int[24];
array[array.length] = 30/0 ;
}
catch (ArrayIndexOutOfBoundsException e){
System.out.println("array size problem");
}
catch (Exception e){
System.out.println("shouldnt be called");
}
System.out.println("third try");
try{
int[] array = new int[24];
array[array.length] = 30/0 ;
}
catch (ArrayIndexOutOfBoundsException e){
System.out.println("array size problem");
}
这样做的问题是,在没有捕获组合的情况下,我可以得到要显示的索引越界异常,所以这就像异常本身之间的层次结构的示例吗?(或者更令人不快的想法是,这是因为计算部分首先完成,因此首先面临异常,因此捕获到异常)。在您编写的代码中从未访问数组。正如您所怀疑的,首先计算语句的右侧,并抛出一个
算术异常
如果您想捕获此代码中的ArrayIndexOutOfBoundsException,则将30/0更改为30/1可以产生
最合适的子异常类型如果已处理,则代码将捕获该异常,但如果未处理,则将通过该异常的超类型捕获
public static void main(String[] args) {
System.out.println("first try");
try {
int[] array = new int[24];
array[array.length] = 30 / 1;// Not divide by zero rather referring array index that is out of bound.
} catch (ArithmeticException e) {
System.out.println("divide by zero");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("array size problem");
} catch (Exception e) {
System.out.println("shouldnt be called");
}
System.out.println("second try");
try {
int[] array = new int[24];
array[array.length] = 30 / 0;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("array size problem");
} catch (Exception e) {
System.out.println("shouldnt be called");
}
System.out.println("third try");
try {
int[] array = new int[24];
array[array.length] = 30 / 0;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("array size problem");
}
}
输出:
first try
array size problem
second try
shouldnt be called
third try
Exception in thread "main" java.lang.ArithmeticException: / by zero
at PerfectPower.main(PerfectPower.java:31)
我假设30/0首先抛出异常,因此从未尝试更新数组,因此没有ArrayIndexOutOfBoundsException。3
try
块中的代码完全相同,那么为什么您希望它们抛出不同的异常呢?--“精神错乱就是一次又一次地做同样的事情,期望得到不同的结果。”