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");
}
}
}
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.