ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3};
        try {
            System.out.println(arr[5]);
        } catch (Exception e) {
            System.out.println("Exception caught");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("AIOOBE caught");
        }
    }
}
  1. A. AIOOBE caught
  2. B. Exception caught
  3. C. Compilation error: AIOOBE catch is unreachable after catch(Exception)
  4. D. It crashes uncaught

Correct answer: C. Compilation error: AIOOBE catch is unreachable after catch(Exception)

ArrayIndexOutOfBoundsException is a subtype of Exception, so placing a broader catch(Exception e) before the narrower catch(ArrayIndexOutOfBoundsException e) makes the second one permanently unreachable — javac flags this as a compile-time error, same rule as ordering RuntimeException before a subtype.

More OOP with C++ and Java questions

Exams that ask this topic