Exception Handling
Multiple Exceptions
Catching different exception types with specific handlers
Interview: Robust error handling — tests understanding of exception ordering, tuple syntax, and specificity
Different operations can raise different types of exceptions. Python lets you handle each type specifically with separate except blocks, or group related exceptions together. The order of except blocks matters — Python checks them top to bottom and uses the first match.
Ordering Rules
- More specific exceptions must come before broader ones
except ZeroDivisionErrorbeforeexcept ArithmeticErrorexcept Exceptionshould always be last (catches everything)- Group related exceptions with tuple:
except (ValueError, TypeError)
Common Pitfall
Putting a broad exception before a specific one makes the specific handler unreachable. Python won't warn you — it just never executes the specific handler.
Use Cases
Parsing different types of user input with specific error messages
API error handling: different responses for network vs parse vs auth errors
File processing: different handlers for missing files vs permission errors
Database operations: unique constraint vs connection vs query errors
Retry logic: retry on network errors, fail immediately on validation errors
Common Mistakes
Putting broad exception before specific one (unreachable code)
Grouping unrelated exceptions together (loses error context)
Not knowing the exception hierarchy (ValueError is not a TypeError)
Using except Exception: when you should handle specific types
Forgetting that except without type catches ALL exceptions including SystemExit