Restrictions on Multi-Catch
You'll learn why Java prevents you from catching exception types that have a parent-child relationship in the same multi-catch clause.
The Subclass Relationship Problem
When using multi-catch syntax, Java enforces an important rule: you cannot combine exception types where one is a subclass of another. This restriction exists because it would create ambiguous and redundant code.
Think of it like sorting packages by size: if you have a bin for "small items" and another for "tiny items," and tiny items are just a subset of small items, why have both? One completely overlaps the other. Java applies this same logic to multi-catch blocks.
Why This Rule Exists
If you tried to catch both a parent exception type and its child type together, the parent would always match any instance of the child. The child type in the multi-catch becomes unnecessary and misleading—it suggests both types are being handled equally, but in reality, the parent dominates.
The compiler rejects this to keep your code clean and your intentions clear.
What You Cannot Do
// COMPILER ERROR: IllegalArgumentException is a subclass of RuntimeException
try {
// code that may throw exceptions
} catch (IllegalArgumentException | RuntimeException e) {
// This won't compile!
}
What You Should Do Instead
Since the parent class catches all its subclasses anyway, just use the parent:
try {
// code that may throw exceptions
} catch (RuntimeException e) {
// Handles both RuntimeException and IllegalArgumentException
}
Or catch them separately if you need different handling:
try {
// code
} catch (IllegalArgumentException e) {
// Handle specifically
} catch (RuntimeException e) {
// Handle more generally
}
Key Takeaway: Multi-catch only allows exception types with no subclass relationship—combining a parent and child type is redundant and results in a compilation error.