ProgrammingVery hardIBM · Deloitte pattern

What happens when this runs, assuming recurse() causes infinite recursion?

What happens when this runs, assuming recurse() causes infinite recursion?
static void recurse() { recurse(); }
public static void main(String[] a) {
    try {
        recurse();
    } catch (Exception e) {
        System.out.print("caught");
    }
}
  1. A. Prints "caught"
  2. B. Compilation error: recurse() has no base case
  3. C. Prints nothing and exits with code 0
  4. D. StackOverflowError propagates uncaught; "caught" is never printed

Correct answer: D. StackOverflowError propagates uncaught; "caught" is never printed

Infinite recursion throws a StackOverflowError, which extends Error, not Exception. catch (Exception e) does not match Error subclasses, so the error propagates uncaught and the JVM terminates abnormally.

More OOP with C++ and Java questions

Exams that ask this topic