java - 打印导致异常错误的特定字符

标签 java exception try-catch

所以我正在做一项作业,我已经解决了所有问题,但作业的最后一部分是打印出通过 try-catch 从用户输入中导致执行错误的特定字符。例如,我输入“Greg Oxley”,问题应该是打印出“”作为错误原因。

我尝试使用Exception.getslacktrace、Exception.getcause()、Exception.getMessage()。最终仍然没有特定的字符。

System.out.print("Enter a single word (letters only, please): ");
        String word = scan.nextLine();
//convert to all upper case
        word = word.toUpperCase();
//count frequency of each letter in string
// Put the body of the first for loop in a try.
// Add a catch that catches the exception, but don’t do anything with it.
//Compile and run your program.
        try{
            for (int i=0; i < word.length(); i++)
                counts[word.charAt(i)-'A']++;
        }
        catch (ArrayIndexOutOfBoundsException Exception)
        {
            System.out.println("Not a Letter: " + Exception.getMessage());

        }

我应该获取导致异常“ArrayIndexOutOfBoundsException”的特定字符并将其打印出来。但相反,我仍然得到“ArrayIndexOutOfBoundsException”打印以及来自 Exception.getMessage() 的输出 - “索引 -12 超出长度 26 的范围”

最佳答案

try 语句之前声明 i 以便能够在 catch 语句中引用它:

int i = 0;

try{
    for (; i < word.length(); i++)
        counts[word.charAt(i)-'A']++;
}
catch (ArrayIndexOutOfBoundsException Exception)
{
    System.out.println("Not a Letter: " + word.charAt(i));

}

如果你想在异常抛出后继续计数,你可以将 try/catch 语句移动到循环内,这样就不需要单独声明 i 了现在可以访问:

for (int i=0; i < word.length(); i++){
    try{
       counts[word.charAt(i)-'A']++;
    }
     catch (ArrayIndexOutOfBoundsException Exception){
         System.out.println("Not a Letter: " + word.charAt(i));
    }
}

关于java - 打印导致异常错误的特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57452115/

相关文章:

java - 在 JTable 中,如何呈现带有脏标记的复选框列?

Java 设计 : Enum state?

javascript - 使用 SyntaxError 捕获无效变量名

java - HashMap恢复原状并发修改异常?

javascript - 捕获 SyntaxError 并运行替代函数

Java 抛出自定义错误

Java LinkedHashMap 获取第一个或最后一个条目

java - 多态性 - 重载/覆盖

Java ExecutorService堆空间问题

python - 有没有一种简单的方法可以注释掉或禁用 python try 语句而无需重新缩进