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");
        }
    }
}
  1. A. AB
  2. B. ABC then the program terminates with an uncaught IllegalStateException
  3. C. AC
  4. 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

Exams that ask this topic