Bird
0
0

Identify the error in this code snippet:

medium📝 Debug Q6 of 15
Java - Exception Handling
Identify the error in this code snippet:
try {
  int x = 5 / 0;
} catch (Exception e) {
  System.out.println("Error caught");
}
catch (ArithmeticException e) {
  System.out.println("Arithmetic error");
}
ASecond catch block is unreachable due to exception hierarchy.
BCatch blocks must be inside try block.
CNo error; code compiles and runs fine.
DMultiple catch blocks for same exception type cause compile error.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze catch block order

    Catch for Exception is general and placed before ArithmeticException which is more specific.
  2. Step 2: Understand unreachable catch blocks

    Since Exception catches all exceptions, the second catch is unreachable, causing compile error.
  3. Final Answer:

    Second catch block is unreachable due to exception hierarchy. -> Option A
  4. Quick Check:

    General catch before specific = unreachable catch [OK]
Quick Trick: Place specific exceptions before general ones in catch [OK]
Common Mistakes:
  • Placing general catch before specific catch
  • Thinking catch blocks can be outside try
  • Assuming multiple catches for same exception allowed

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes