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?
Scenario | Use Multiple Catches? | Reason |
---|---|---|
Different exceptions need different actions | ✅ Yes | Enables tailored handling logic |
You want detailed logs for debugging | ✅ Yes | Lets you isolate causes clearly |
You don’t care about the exception type | ❌ Not needed | A single generic catch may suffice |
You’re working with checked + unchecked exceptions | ✅ Yes | Keeps 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.