ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
public class Main {
    public static void main(String[] a) {
        int[] arr = {1, 2, 3};
        try {
            System.out.print(arr[5]);
        } catch (Exception e) {
            System.out.print("caught " + e.getClass().getSimpleName());
        }
    }
}
  1. A. caught Exception
  2. B. caught ArrayIndexOutOfBoundsException
  3. C. Compile-time error: catch (Exception e) cannot catch an array index error
  4. D. The program crashes: ArrayIndexOutOfBoundsException is not a subtype of Exception

Correct answer: B. caught ArrayIndexOutOfBoundsException

ArrayIndexOutOfBoundsException is an unchecked RuntimeException, and all RuntimeExceptions are subtypes of Exception, so catch (Exception e) catches it. e.getClass().getSimpleName() reports the actual runtime class, ArrayIndexOutOfBoundsException, not the static catch type.

More OOP with C++ and Java questions

Exams that ask this topic