我试图捕获多个异常,但无法捕获。我只发现了一个例外。
class Main {
public static void main(String[] args) {
try {
int array[] = new int[10];
array[10] = 30 / 0;
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
}
在语句array[10] = 30 / 0;
中,您可以看到编译器首先要做的是计算30除以0,这肯定会引发算术异常。由于赋值操作前的语句抛出异常,因此它将从try块中断并跳到catch (ArithmeticException e)
块,array[invalidIndex]
从不执行,因此它永远不会抛出ArrayIndexOutOfBoundsException
。