This guide explains catching multiple exception types through a focused Python example. You will learn the behavior to expect, why it matters in a real program, and how to recognize the common mistakes before applying it in your own project.
What You Will Learn
An except clause can handle a tuple of related exception types. Use the tuple when the same recovery action is appropriate for each failure.
When and Why to Use It
The following example focuses on a practical use of Catching Multiple Exception Types.
Step-by-Step Example
def get_selected_item(items, position):
try:
return items[position]
except (IndexError, TypeError) as error:
return f"Invalid selection: {type(error).__name__}"
print(get_selected_item(["A", "B"], 5))
Understanding the Example
An out-of-range index causes IndexError and returns a message. A noninteger index could cause TypeError and enter the same handler.
Expected Output
Invalid selection: IndexError
Important Behavior and Edge Cases
Do not combine unrelated exceptions just because they are easy to type; distinct causes may need distinct user messages.
Try It Yourself
Handle both KeyError and TypeError when looking up a value in an optional mapping.
Common Beginner Mistakes
- Do not combine unrelated exceptions just because they are easy to type; distinct causes may need distinct user messages.
- Handling the symptom rather than identifying the failing operation, or letting a broad exception handler hide defects.
- Skipping the practice step and assuming the example covers every input. Test at least one normal case and one edge case relevant to this topic.
Key Takeaways
- An except clause can handle a tuple of related exception types.
- An out-of-range index causes IndexError and returns a message.
- Apply the technique deliberately, checking its documented input requirements and failure behavior before integrating it into a larger project.