为什么不打印 R?为什么输出是 PQST?

Why R is not being printed ? why the output is PQST?

这是我的代码。这里 PQRST 应该是输出,但 R 没有被打印出来。我不明白为什么?

class Validator{
    public int[] studentId = { 101, 102, 103 };

    public void validateStudent(int id) {
        try {
            for (int index = 0; index <= studentId.length; index++) {
                if (id == studentId[index])
                    System.out.println("P");
            }
        } finally {
            System.out.println("Q");
        }
    }
}


public class Tester {
    public static void main(String[] args) {
        Validator validator = new Validator();
        try {
            validator.validateStudent(101);
            System.out.print("R");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("S");
        } finally {
            System.out.println("T");
        }
    }
}

您的代码目前正在抛出 ArrayIndexOutOfBoundsException。因为你超出了数组的长度。这个

for (int index = 0; index <= studentId.length; index++) {

应该是

for (int index = 0; index < studentId.length; index++) {

但是 S 不会被打印(因为它不会抛出 Exception)。

今天是学习如何使用调试器的非常棒的一天。

问题在于 validateStudent 方法以 ArrayIndexOutOfBoundsException exception 结尾,因此 System.out.print ("R"); 语句不会执行。当异常发生时。

我可能会尝试以不同的方式解决这个问题,并且不会有例外,在我看来,就逻辑和处理而言,这非常复杂。它只是减慢了本可以更简单的程序。