Java — Identify the issue with catch ordering (general Exception before specific ArithmeticException): try { int x = 0; int y = 5 / x; } catch (Exception e) { System.out.println("Exception"); } catch (ArithmeticException ae) { System.out.println(" Arithmetic Exception"); } System.out.println("finished");

Difficulty: Easy

Correct Answer: Compilation fails.

Explanation:


Introduction / Context:
This question checks knowledge that more specific exceptions must be caught before more general ones; otherwise the specific catch block is unreachable, causing a compile-time error.



Given Data / Assumptions:

  • Exception is the superclass of ArithmeticException.
  • The code lists catch (Exception) before catch (ArithmeticException).


Concept / Approach:
Java requires catch blocks to be ordered from most specific to most general. If a general catch appears first, any subsequent specific catch for the same hierarchy is unreachable.



Step-by-Step Solution:

The compiler analyzes the catch sequence.Since Exception would catch ArithmeticException, the latter catch can never be reached.Java flags this as an error: unreachable catch block.


Verification / Alternative check:
Swap the two catch blocks: catch (ArithmeticException) first, then catch (Exception). The code will then compile and run printing "Exception" if you change the divisor to a non-zero value, or "Arithmetic Exception" for division by zero.



Why Other Options Are Wrong:
They assume execution proceeds; however compilation fails before runtime.



Common Pitfalls:
Believing that multiple catches for the same exception type could both run, or that order does not matter.



Final Answer:
Compilation fails.

More Questions from Exceptions

Discussion & Comments

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