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");
    }
}
  1. A. ABCD
  2. B. ABD
  3. C. AB
  4. 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

Exams that ask this topic