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");
}
}
}- A. generic
- B. boom
- C. Compile-time error: catch (Exception e) is unreachable after catch (RuntimeException e)
- 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
- Does this compile? java public class Main { public static void main(String[] a) { try { throw new RuntimeException(); } catch (Exception…
- What is printed? java class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) {…
- What is printed? java public class Main { public static void main(String[] args) { String a = "hello"; String b = "hello"; String c = new…
- What is printed? java public class Main { public static void main(String[] args) { String a = "hello"; String c = new…
- What is printed? java import java.util.; public class Main { public static void main(String[] args) { List<Integer> nums =…
- What is printed? java public class Main { static void risky(int x) throws Exception { if (x < 0) throw new Exception("neg")…