ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
public class Main {
public static void main(String[] args) {
try {
level1();
} catch (RuntimeException e) {
System.out.println("outer caught: " + e.getMessage());
}
}
static void level1() {
try {
level2();
} catch (NullPointerException e) {
System.out.println("level1 caught NPE");
}
}
static void level2() {
throw new IllegalStateException("deep");
}
}- A. level1 caught NPE
- B. outer caught: deep
- C. Compilation error: level1 must declare throws
- D. The program crashes with no output
Correct answer: B. outer caught: deep
level1's catch only matches NullPointerException, so the actual IllegalStateException is not caught there and propagates up through level1's call stack to main, whose catch(RuntimeException e) does match it (IllegalStateException is a RuntimeException), printing "outer caught: deep".
More OOP with C++ and Java questions
- What is printed? java class MyException extends RuntimeException { MyException(String m) { super(m); } } public class Main { public static…
- What is printed? java public class Main { public static void main(String[] args) { int i = 0; while (true) { try { i++; if (i == 3) break…
- What is printed? java static int f() { int x = 1; try { return x; } finally { x = 2; } } public static void main(String[] a) {…
- What is printed? java static void f() throws Exception { try { throw new RuntimeException("A"); } finally { throw new…
- What is printed? java for (int i = 0; i < 3; i++) { try { if (i == 1) continue; System.out.print(i); } finally { System.out.print("f"); } }
- What is printed? java try { try { throw new java.io.IOException("io-fail"); } catch (java.io.IOException e) { throw new…