ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
try {
sb.append("A");
method2(sb);
} catch (Exception e) {
sb.append("C");
} finally {
sb.append("D");
}
System.out.println(sb);
}
static void method2(StringBuilder sb) throws Exception {
sb.append("B");
throw new Exception("fail");
}
}- A. ABCD
- B. ABD
- C. AB
- D. ACD
Correct answer: A. ABCD
method2 appends B then throws; the exception propagates to main's catch, which appends C, and finally always runs afterward, appending D, giving the full accumulated string "ABCD".
More OOP with C++ and Java questions
- What is printed? cpp struct Logger { Logger() { cout << "open "; } ~Logger() noexcept(false) { cout << "close "; throw…
- What is printed? java public class Main { public static void main(String[] args) { try { level1(); } catch (RuntimeException e) {…
- 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…