ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
public class Main {
public static void main(String[] args) throws Exception {
try {
method1();
} catch (RuntimeException e) {
System.out.print("outer caught: " + e.getMessage());
}
}
static void method1() {
try {
throw new IllegalStateException("bad state");
} catch (NullPointerException e) {
System.out.print("npe");
}
}
}- A. npe
- B. outer caught: bad state
- C. Compile-time error: method1 must declare throws IllegalStateException
- D. Nothing: the exception is silently swallowed
Correct answer: B. outer caught: bad state
IllegalStateException does not match the catch (NullPointerException e) in method1, so it is not caught there and propagates up (unchecked exceptions need no throws declaration). main's catch (RuntimeException e) matches it (IllegalStateException is a RuntimeException), printing "outer caught: bad state".
More OOP with C++ and Java questions
- What is printed? java public class Main { static class Resource implements AutoCloseable { public void close() { System.out.print("closed…
- What happens when this is compiled? java class Base { void risky() throws java.io.IOException {} } class Sub extends Base { @Override void…
- What is printed? java public class Main { public static void main(String[] args) { Object o = "text"; try { Integer n = (Integer) o…
- What is printed? java public class Main { static int divide(int a, int b) { try { return a / b; } catch (ArithmeticException e) { return…
- What is printed? java import java.util.; public class Main { public static void main(String[] args) { Map<String, Integer> m = new…
- What is printed? java public class Main { public static void main(String[] args) { StringBuilder sb = new StringBuilder("abc"); try {…