Bird
0
0

What is wrong with this Java code snippet?

medium📝 Debug Q7 of 15
Java - Exception Handling

What is wrong with this Java code snippet?

try {
  int result = 10 / 0;
} catch (Exception e) {
  System.out.println("Exception caught");
} catch (ArithmeticException e) {
  System.out.println("Arithmetic Exception caught");
}
AThe catch blocks are ordered incorrectly; specific exceptions must come before general ones
BThe try block does not throw any exception
CArithmeticException cannot be caught
DThere is no error; code is correct
Step-by-Step Solution
Solution:
  1. Step 1: Understand catch block order

    In Java, catch blocks must be ordered from most specific to most general exceptions.
  2. Step 2: Analyze code

    The general Exception catch block comes before ArithmeticException, causing a compile-time error.
  3. Final Answer:

    The catch blocks are ordered incorrectly; specific exceptions must come before general ones -> Option A
  4. Quick Check:

    Specific exceptions first, then general [OK]
Quick Trick: Order catch blocks from specific to general [OK]
Common Mistakes:
  • Placing general Exception catch block before specific exceptions
  • Assuming catch block order does not matter
  • Ignoring compile-time errors from incorrect order

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes