Can we use multiple catches? When can we use multiple catches?

Yes, Java allows multiple catch blocks after a try block to handle different types of exceptions independently.

🎯 Why Use Multiple Catch Blocks?

  • To handle different exception types with tailored logic.
  • To avoid catching a generic exception and suppressing useful details.
  • To write cleaner, more predictable, and safe code.

🔧 Syntax Example

try {
    // risky code
    int result = 10 / 0;
    String text = null;
    System.out.println(text.length());
} catch (ArithmeticException e) {
    System.out.println("Arithmetic error: " + e.getMessage());
} catch (NullPointerException e) {
    System.out.println("Null pointer issue: " + e.getMessage());
} catch (Exception e) {
    System.out.println("Some other error: " + e.getMessage());
}

📝 Key Notes:

  • Each catch handles a specific type of exception.
  • The most specific exceptions come first, followed by more general ones (like Exception).
  • Only one matching catch block is executed per try block.

🔄 When Should You Use Multiple Catch Blocks?

ScenarioUse Multiple Catches?Reason
Different exceptions need different actions✅ YesEnables tailored handling logic
You want detailed logs for debugging✅ YesLets you isolate causes clearly
You don’t care about the exception type❌ Not neededA single generic catch may suffice
You’re working with checked + unchecked exceptions✅ YesKeeps handling clean and compliant

🧠 Bonus: Java 7 Multi-Catch

If you want to handle multiple exceptions with the same logic, use multi-catch:

try {
    // risky code
} catch (IOException | SQLException e) {
    System.out.println("Handled: " + e);
}

📌 Important: In multi-catch, the exception variable e is implicitly final, meaning you can’t reassign it.

🏁 Crucial Interview Takeaways

  • ✅ Multiple catch blocks = clean, modular, specialized exception handling.
  • 🚫 Don’t put generic Exception before specific ones—it’ll make the rest unreachable (compile-time error).
  • 🔐 Use multi-catch only when the same handling applies to all listed exceptions.
  • 📚 Always catch checked exceptions, and handle unchecked exceptions thoughtfully.

Leave a Reply

Your email address will not be published. Required fields are marked *