Java Multiple Exceptions
⚠️ Java Multiple Exceptions
In Java, a single try block can throw more than one type of exception. To handle this, we can use:
-
Multiple catch blocks
-
Single catch block using multi-catch (Java 7+)
-
Catching the parent exception class
1. Multiple catch Blocks
Different exceptions can be handled separately.
Example:
🔍 Rule: Order of catch Matters
More specific exceptions must come before general exceptions.
Otherwise, the compiler shows an error.
❌ Wrong:
Because Exception already handles everything.
2. Multi-Catch (Java 7+)
To avoid writing many catch blocks, we can combine exceptions using |:
⚠️ Multi-Catch Rule
You cannot combine exceptions with parent-child relationship.
Example:
❌ Invalid — because ArithmeticException is already included in Exception.
3. Catching Parent Exception
Instead of multiple catches, you can catch the superclass Exception.
🧠 Summary Table
| Method | Catch Style | Best Use Case |
|---|---|---|
| Multiple catch blocks | Specific exceptions | Precise control |
| Multi-catch ( | ) | One block handles multiple exception types |
| Single parent catch | Exception e |
General handling/logging |
