ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
public class Main {
public static void main(String[] a) {
try {
System.out.print("A");
throw new RuntimeException();
} catch (RuntimeException e) {
System.out.print("B");
throw new IllegalStateException();
} finally {
System.out.print("C");
}
}
}- A. AB
- B. ABC then the program terminates with an uncaught IllegalStateException
- C. AC
- D. ABC with no error
Correct answer: B. ABC then the program terminates with an uncaught IllegalStateException
The try throws, the catch runs (printing B after A), then itself throws a new exception. Before that new exception propagates out of the method, finally still runs (printing C). Since nothing catches IllegalStateException, the program terminates abnormally after printing ABC.
More OOP with C++ and Java questions
- Does this compile? java class MyException extends Exception {} class Demo { void risky() throws MyException { throw new MyException(); }…
- Does this compile? java class Demo { void risky() { throw new IllegalArgumentException(); } void call() { risky(); } }
- What is printed? java public class Main { public static void main(String[] a) { int[] arr = {1, 2, 3}; try { System.out.print(arr[5]); }…
- What is printed? java public class Main { static void a() { b(); } static void b() { c(); } static void c() { throw new…
- 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) {…