In Java, what happens when a method throws an Error that is not caught by catch(Exception), with a finally block present? public class X { public static void main(String [] args) { try { badMethod(); System.out.print("A"); } catch (Exception ex) { System.out.print("B"); } finally { System.out.print("C"); } System.out.print("D"); } public static void badMethod() { throw new Error(); // Line 22 } }

Difficulty: Medium

Correct Answer: C is printed before exiting with an error message.

Explanation:


Introduction / Context:
This tests your understanding of Java's Throwable hierarchy and catch matching. Error is not a subtype of Exception; therefore catch(Exception) does not handle an Error. However, finally still executes.



Given Data / Assumptions:

  • badMethod() throws new Error().
  • try prints "A" only if no exception or error interrupts execution.
  • catch catches only Exception (and its subclasses), not Error.
  • finally always executes.
  • Printing "D" happens only if control reaches after the try/catch/finally.


Concept / Approach:
Error represents serious problems that a reasonable application should not try to catch. Since Error is not an Exception, the catch(Exception) block will not handle it. The JVM unwinds the stack after finally runs.



Step-by-Step Solution:

badMethod throws Error → control jumps to finally (catch does not match).finally prints "C".Program terminates with an uncaught Error; "A" and "D" are not printed.


Verification / Alternative check:
Change the catch to catch(Throwable) or catch(Error) to handle it; then "C" would still print, and the program could continue to print "D".



Why Other Options Are Wrong:
They imply catch(Exception) would handle Error or that finally does not run, both incorrect.



Common Pitfalls:
Assuming Exception catches everything under Throwable; forgetting the special place of Error and its subclasses.



Final Answer:
C is printed before exiting with an error message.

More Questions from Exceptions

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion