ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
public class Main {
    public static void main(String[] args) {
        try {
            Object[] arr = new String[3];
            arr[0] = 100;
        } catch (ArrayStoreException | ArrayIndexOutOfBoundsException e) {
            System.out.println("caught: " + e.getClass().getSimpleName());
        }
    }
}
  1. A. caught: ArrayIndexOutOfBoundsException
  2. B. caught: ArrayStoreException
  3. C. Compilation error: multi-catch requires unrelated exception types without a common ancestor other than Throwable in some versions
  4. D. It crashes uncaught

Correct answer: B. caught: ArrayStoreException

A multi-catch clause (A | B) is legal as long as neither type is a subclass of the other; ArrayStoreException and ArrayIndexOutOfBoundsException are unrelated siblings under RuntimeException, so this compiles fine. At run time, storing an Integer into what is really a String[] throws ArrayStoreException, caught here.

More OOP with C++ and Java questions

Exams that ask this topic