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");
}- A. Compilation error: unreachable catch
- B. A
- C. B
- 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
- Does this compile (Java 7+)? java static void m() throws java.io.IOException, java.sql.SQLException { try { if (Math.random() < 2) throw…
- Does this compile? java class A { void m() throws java.io.IOException {} } class B extends A { @Override void m() throws…
- What is printed, and what happens to the RuntimeException? java static int f() { try { throw new RuntimeException("x"); } finally { return…
- What is printed? java class MyEx extends RuntimeException { public String getMessage() { return "custom:" + super.getMessage(); } } public…
- Does this compile? java interface I { void m() throws java.io.IOException; } class C implements I { public void m() throws…
- 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) {…