ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
class MyException extends RuntimeException {
MyException(String m) { super(m); }
}
public class Main {
public static void main(String[] args) {
try {
try {
throw new MyException("inner");
} catch (IllegalArgumentException e) {
System.out.print("wrong-catch ");
}
} catch (MyException e) {
System.out.print("right-catch:" + e.getMessage());
}
}
}- A. wrong-catch
- B. right-catch:inner
- C. wrong-catch right-catch:inner
- D. Compilation error: MyException is never caught
Correct answer: B. right-catch:inner
MyException is not an IllegalArgumentException, so the inner catch doesn't match and the exception propagates to the outer try's catch(MyException), which correctly matches, printing "right-catch:inner". The inner catch block is simply skipped entirely, not partially entered.
More OOP with C++ and Java questions
- 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…
- What happens when this runs? java class Test { static void m() { throw new ArithmeticException("boom"); } public static void main(String[]…