Bird
0
0

Given this code, what is the best way to handle exceptions?

hard📝 Application Q9 of 15
Java - Exception Handling

Given this code, what is the best way to handle exceptions?

try {
  // code that may throw IOException or SQLException
} catch (Exception e) {
  System.out.println("Exception caught");
} catch (IOException e) {
  System.out.println("IO Exception caught");
} catch (SQLException e) {
  System.out.println("SQL Exception caught");
}
ACatch IOException and SQLException only
BCatch Exception first, then IOException and SQLException
CCatch only Exception
DCatch IOException and SQLException before Exception
Step-by-Step Solution
Solution:
  1. Step 1: Analyze catch order

    Exception is superclass of IOException and SQLException.
  2. Step 2: Correct catch order

    Subclass exceptions must be caught before superclass Exception to avoid unreachable code.
  3. Final Answer:

    Catch IOException and SQLException before Exception -> Option D
  4. Quick Check:

    Subclass catches before superclass catch [OK]
Quick Trick: Always catch specific exceptions before general Exception [OK]
Common Mistakes:
  • Placing general Exception catch before specific exceptions
  • Ignoring unreachable catch block errors
  • Catching only general Exception hides specific handling

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes