尽管有通用的 Exception e catch,程序仍抛出异常

Program throwing exception despite generic Exception e catch

public class TryCatch {
    public static void main(String[] args) {

    int Score[] = {5,3,9};  //my array
    Scanner sc = new Scanner(System.in);
    boolean flag=true; //boolean for the while loop that will keep on asking for input till the input is correct

    System.out.println("Enter index: ");

    int ind = sc.nextInt(); //taking input

    while(flag){
        try {
            System.out.println("Value at index is = " + Score[ind]);
            flag= false;      //if input is correct, the bool turns false and loop stops

        } catch (Exception e) {  
            System.out.println("Enter a valid value!");
            ind = sc.nextInt();  //should ask for input again if the input isn't right
        }
    }

}
}

所以我遇到的问题是 catch 块适用于 ArrayOutOfBound 异常,但当我输入其他字符(如字母)时则无效。我该怎么办?

更新:

我通过在 catch 块中创建扫描器 class 对象的新实例来修复该错误。

sc = new Scanner(System.in);

谢谢大家的回答。

我认为您需要使用管道运算符分隔异常(当捕获多种类型时)(SQLException | IOException e) 例如。

发生这种情况是因为您要求在 catch 中输入整数,这在其他任何地方都没有处理,试试这个:

int ind; //taking input

while(flag){
    try {
        find = sc.nextInt();
        System.out.println("Value at index is = " + Score[ind]);
        flag= false;      //if input is correct, the bool turns false and loop stops

    } catch (Exception e) {  
        System.out.println("Enter a valid value!");
        continue;
    }
}

问题是在 try 块之外抛出了异常。您在 try-catch 块之前或在 catch 块中从键盘读取。

如果在 catch 块中抛出异常,则不会捕获该异常。另外你需要用 nextLine 清除输入,否则你会得到一个无限循环,正确的代码如下:

System.out.println("Enter index: ");

while (flag) {

    try {
        int ind = sc.nextInt(); //taking input
        System.out.println("Value at index is = " + Score[ind]);
        flag = false;      //if input is correct, the bool turns false and loop stops
    
    } catch (Exception e) {
        System.out.println("Enter a valid value!");
        sc.nextLine();
        continue;
    }
}

您需要再次初始化扫描器 class 对象以关闭之前的扫描器并转储其中的所有输入。

将此行添加到 catch 块的末尾-

sc = new Scanner(System.in);