Java — Determine output when throwing a subclass exception and catching a superclass: class Exc0 extends Exception { } class Exc1 extends Exc0 { } /* Line 2 */ public class Test { public static void main(String args[]) { try { throw new Exc1(); /* Line 9 */ } catch (Exc0 e0) /* Line 11 */ { System.out.println("Ex0 caught"); } catch (Exception e) { System.out.println("exception caught"); } } }
-
AEx0 caught
-
Bexception caught
-
CCompilation fails because of an error at line 2.
-
DCompilation fails because of an error at line 9.
Answer
Correct Answer: Ex0 caught
Explanation
Introduction / Context:This validates understanding of exception inheritance and matching. A catch for a superclass type can handle exceptions of its subclass.
Given Data / Assumptions:
- Exc1 extends Exc0, and both extend Exception (directly or indirectly).
- The code throws new Exc1().
- First catch handles Exc0, second catch handles Exception.
Concept / Approach:Java chooses the first catch whose parameter type is assignable from the thrown exception type. Since Exc0 is a superclass of Exc1, the first catch matches.
Step-by-Step Solution:
throw new Exc1() executes.catch (Exc0 e0) matches and executes, printing "Ex0 caught".Subsequent catch blocks are skipped.Verification / Alternative check:Swap the two catch blocks and observe that "exception caught" would execute instead because Exception would match first.
Why Other Options Are Wrong:No compilation errors exist at the stated lines; the subclass relationship is valid. The second catch does not run because the first one already handled the exception.
Common Pitfalls:Expecting a more general catch to run after a specific one; only the first matching catch executes.
Final Answer:Ex0 caught