-2

Here's my code. Here PQRST should be the output but R is not printed. I don't understand why ?

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");
        }
    }
}
Holger
  • 285,553
  • 42
  • 434
  • 765
  • 1
    *PQRST should be the output* That is not possible with the code as shown - R and S are mutually exclusive, since if R is printed, there's nothing following that can throw the out-of-bounds exception to print S. – passer-by Feb 05 '22 at 20:34

2 Answers2

0

Your code is currently throwing an ArrayIndexOutOfBoundsException. Because you exceed the length of the array. This

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

should be

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

But then S will not be printed (because it won't throw an Exception).

Today is an excellent day to learn how to use a debugger.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

The problem is that the validateStudent method ends with an ArrayIndexOutOfBoundsException exception, and therefore the System.out.print ("R"); statement does not execute. When the exception happens.

I would probably try to solve this problem a little differently and not with exceptions, which in my opinion are quite complicated in terms of logic and processing. It simply slows down the program that could be more simple.