ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
public class Main {
    static void a() { b(); }
    static void b() { c(); }
    static void c() { throw new RuntimeException("boom"); }
    public static void main(String[] args) {
        try {
            a();
        } catch (RuntimeException e) {
            System.out.print(e.getMessage());
        } catch (Exception e) {
            System.out.print("generic");
        }
    }
}
  1. A. generic
  2. B. boom
  3. C. Compile-time error: catch (Exception e) is unreachable after catch (RuntimeException e)
  4. D. Compile-time error: cannot catch the same exception type twice

Correct answer: B. boom

The exception propagates unwinding through c, b, a up to main, where the first matching catch clause, catch (RuntimeException e), handles it directly (RuntimeException is more specific and listed first), printing its message "boom". The second catch is reachable for other Exception subtypes and is not an error, since RuntimeException and Exception are listed in a valid specific-to-general order.

More OOP with C++ and Java questions

Exams that ask this topic