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");
}
}- A. Prints "caught"
- B. Compilation error: recurse() has no base case
- C. Prints nothing and exits with code 0
- 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
- What is printed? java class AEx extends Exception {} class BEx extends AEx {} // in main, wrapped in throws Exception: try { throw new…
- Does this compile (Java 7+)? java static void m() throws java.io.IOException, java.sql.SQLException { try { if (Math.random() < 2) throw…
- Does this compile? java class A { void m() throws java.io.IOException {} } class B extends A { @Override void m() throws…
- What is printed, and what happens to the RuntimeException? java static int f() { try { throw new RuntimeException("x"); } finally { return…
- What is printed? java class MyEx extends RuntimeException { public String getMessage() { return "custom:" + super.getMessage(); } } public…
- Does this compile? java interface I { void m() throws java.io.IOException; } class C implements I { public void m() throws…