In this lesson, you will learn how to handle multiple independent errors simultaneously using Python’s ExceptionGroup.
The Problem: Handling Concurrent Errors
Up until now, you have used try-except blocks to catch one error at a time. This works perfectly for linear code. However, when working with concurrent operations—where multiple tasks might fail at the exact same time—a single except block isn't enough. You need a way to group these errors together so you can inspect and address each one individually.
Introducing Exception Groups
An ExceptionGroup is a special container that holds multiple, independent exceptions. Instead of your program crashing at the first error it encounters, it can collect all failures from different tasks into one group. You can then use the special except* syntax to "split" the group and handle specific types of errors inside it.
Here is how you can handle a group of mixed errors:
try:
# Simulating a scenario where two tasks fail
raise ExceptionGroup("Task Failures", [
ValueError("Invalid value in task 1"),
TypeError("Type mismatch in task 2")
])
except* ValueError as eg:
print(f"Caught ValueErrors: {eg.exceptions}")
except* TypeError as eg:
print(f"Caught TypeErrors: {eg.exceptions}")
Why except*?
The except* syntax is unique because it iterates through the ExceptionGroup and matches the exception types you specify. Each except* block will receive an ExceptionGroup containing only the errors that match that specific type. If there are leftover errors in the group that weren't caught by your except* blocks, Python will automatically re-raise them, ensuring no silent failures occur.
This approach is highly effective for robust programs that perform multiple independent operations, as it allows you to maintain control over the entire landscape of potential failures rather than just stopping at the first bump in the road.
Key Takeaway: Use ExceptionGroup and the except* syntax to catch and manage multiple, independent errors triggered by concurrent operations in a single workflow.