ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
class AEx extends Exception {}
class BEx extends AEx {}
// in main, wrapped in throws Exception:
try {
    throw new BEx();
} catch (BEx e) {
    System.out.print("B");
} catch (AEx e) {
    System.out.print("A");
}
  1. A. Compilation error: unreachable catch
  2. B. A
  3. C. B
  4. D. AB

Correct answer: C. B

Catch blocks are tried in order, and BEx (the subclass) is listed before AEx (the superclass), so this compiles fine. The thrown BEx matches the first, more specific catch and prints "B".

More OOP with C++ and Java questions

Exams that ask this topic