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());
}
}
}- A. caught: ArrayIndexOutOfBoundsException
- B. caught: ArrayStoreException
- C. Compilation error: multi-catch requires unrelated exception types without a common ancestor other than Throwable in some versions
- 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
- What is printed? cpp void f() { try { throw 10; } catch (double d) { cout << "double:" << d; } catch (int i) { cout << "int:" << i; } }…
- What is printed? java public class Main { public static void main(String[] args) { int[] arr = {1, 2, 3}; try {…
- What is printed? java class Base { final void secure() { System.out.print("Base.secure"); } } class Derived extends Base { // void…
- What is printed? cpp class Base { public: virtual void f() final { cout << "Base::f "; } }; class Derived : public Base { public: // void…
- What is printed? cpp struct Base { Base() { cout << "Base() "; } }; struct Mixin1 { Mixin1() { cout << "Mixin1() "; } }; struct Mixin2 {…
- What is printed? java enum Operation { ADD { public int apply(int a, int b) { return a + b; } }, MULTIPLY { public int apply(int a, int b)…