【发布时间】:2023-03-03 01:54:01
【问题描述】:
我在尝试捕获 Java 中的 List 的 IndexOutOfBoundsException 时遇到了一些问题。所以我用 2 个元素声明了我的列表:
List<String> list = new ArrayList<>(Arrays.asList("item1", "item2"));
然后我尝试做一个try catch:
do {
for (int i = 0; i < list.size(); i++) {
System.out.print("(" + (i + 1) + ")" + list.get(i));
}
System.out.println(" ");
try{
option = sc.nextInt();
} catch (IndexOutOfBoundsException e){
System.out.println("Invalid option");
sc.next();
continue;
} catch (InputMismatchException e) {
System.out.println("Option input mismatch.");
sc.next();
continue;
}
sc.nextLine();
if (option == 1) {
System.out.print("Enter name: ");
// scanner takes in input
} else if (option == 2) {
System.out.print("Enter desc: ");
// scanner takes in input
}
type = list.get((option - 1));
} while (option <= 0 || option >= 3);
但是,当我输入任何大于 2 的选项时,它会抛出 IndexOutOfBounds 异常,但我认为我已经为它做了尝试捕获?
提前致谢。
【问题讨论】:
-
您在发布的代码中没有使用
list做任何事情? -
为什么
nextInt会抛出IndexOutOfBoundsException?请包含实际抛出它的代码。 -
如果异常来自您的
list,那么try块必须包含使用您的list的代码才能捕获异常。 -
可能来自其他地方,请显示堆栈跟踪
-
你为什么要这样实例化列表?您可以简化该行 List
itemList = Arrays.asList("item 1", "item2");
标签: java list indexoutofboundsexception