捕获 ArrayOutOfBoundsException
catching ArrayOutOfBoundsException
我正在为我的学校做一个项目,我已经处理了所有异常,但我就是无法处理 ArrayOutOfBoundsException。
所以我在 Whosebug 上搜索了一个解决方案,它说使用 IndexOutOfBoundsException(link 到解决方案:why is it not catching the arrays out of bound?)
但它没有用。请帮忙?
这是我的代码:
for (int i = 0; i < 4; i++) {
System.out.println(fruit[i] + fruitprice[i]);
}
System.out.println("\n" + "please enter the number marked for the icecream you want to buy");
do {
x = 0;
try {
icenum1 = Integer.parseInt( in .readLine()) - 1;
} catch (NumberFormatException n) {
System.out.println("please enter in numbers and not in words.... please try again");
x = 1;
} catch (IndexOutOfBoundsException e) {
System.out.println("please enter a number out of the given numbers and not any other number");
x = 1;
}
} while (x != 0);
System.out.print("\u000c");
System.out.println("your choice is " + fruit[icenum1]);
如果它仍然符合您的代码逻辑,请将这些行移动到您的 try 块中。
System.out.print("\u000c");
System.out.println("your choice is " + fruit[icenum1]);
如果抛出 IndexOutOfBoundException
,它将从第二行开始,因为它会尝试访问当前数组中不存在的索引。
我正在为我的学校做一个项目,我已经处理了所有异常,但我就是无法处理 ArrayOutOfBoundsException。 所以我在 Whosebug 上搜索了一个解决方案,它说使用 IndexOutOfBoundsException(link 到解决方案:why is it not catching the arrays out of bound?) 但它没有用。请帮忙? 这是我的代码:
for (int i = 0; i < 4; i++) {
System.out.println(fruit[i] + fruitprice[i]);
}
System.out.println("\n" + "please enter the number marked for the icecream you want to buy");
do {
x = 0;
try {
icenum1 = Integer.parseInt( in .readLine()) - 1;
} catch (NumberFormatException n) {
System.out.println("please enter in numbers and not in words.... please try again");
x = 1;
} catch (IndexOutOfBoundsException e) {
System.out.println("please enter a number out of the given numbers and not any other number");
x = 1;
}
} while (x != 0);
System.out.print("\u000c");
System.out.println("your choice is " + fruit[icenum1]);
如果它仍然符合您的代码逻辑,请将这些行移动到您的 try 块中。
System.out.print("\u000c");
System.out.println("your choice is " + fruit[icenum1]);
如果抛出 IndexOutOfBoundException
,它将从第二行开始,因为它会尝试访问当前数组中不存在的索引。