Java try catch 不处理 IndexOutOfBoundsException

标签 java list indexoutofboundsexception

当 try catch Java 中的列表的 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 异常,但我认为我已经对其进行了 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
        }
        try {
            type = list.get((option - 1));
        } catch (IndexOutOfBoundsException e) {
            System.out.println("Invalid option");
            option=3;
        }
    } while (option <= 0 || option >= 3);

我在 type = list.get((option - 1)); 添加了新的 try-catch 为了强制用户重新输入选项,我将在捕获原因处将选项设置为 3

关于Java try catch 不处理 IndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36136526/

相关文章:

java - 我可以在 war 中捆绑更新版本的 Nashorn 吗?

java - 如何在 eclipse 中添加gradle?

python - 为什么 Python 中一个变量可以全局访问,而另一个则不能?

r - 在列表上应用 paste0 函数

java - 从SQLite数据库删除项目时出错

java - BigDecimal toEngineeringString 不起作用

java - Spring Framework中new关键字的作用

c++ - 将 std::list::remove_if 与 MyClass 函数一起使用

Netty:奇怪的 IndexOutOfBoundsException:readerIndex + 长度超过 writerIndex

java - 打印数组/反转数组