Handling Multiple Errors with ExceptionGroup
When multiple concurrent tasks fail simultaneously, raising one error drops the other traces. Python 3.11 added `ExceptionGroup` and `except*` syntax to pattern-match, isolate, and handle multiple concurrent failures cleanly 💥🛡️.
import asyncio
async def fail_auth():
raise PermissionError("Token expired")
async def fail_db():
raise ConnectionError("Pool exhausted")
async def main():
try:
async with asyncio.TaskGroup() as tg:
tg.create_task(fail_auth())
tg.create_task(fail_db())
except* PermissionError as eg:
print(f"Handled auth errors: {len(eg.exceptions)} 🛡️")
except* ConnectionError as eg:
print(f"Handled db errors: {len(eg.exceptions)} 🛑")
asyncio.run(main())
# 23. Handling Multiple Errors with ExceptionGroup Before Python 3.11, if three coroutines threw exceptions concurrently under `asyncio.gather()`, Python either chose one at random to propagate or forced you to parse a list of raw exception instances 🛑. ```python try: async with asyncio.TaskGroup() as tg: tg.create_task(task_one()) tg.create_task(task_two()) except* ValueError as eg: # Catches only the ValueError branch of the exception tree: for e in eg.exceptions: print(f"Caught: {e}") ``` ### ExceptionGroup Architecture 1. **Tree of Errors**: An `ExceptionGroup` forms a hierarchical tree containing all unhandled exceptions raised across tasks within that group 💥. 2. **Selective Filtering (`except*`)**: Unlike traditional `except` which halts at the first matching clause, multiple `except*` blocks can execute in sequence, each handling its slice of the group. 3. **Unmatched Remainder**: Any exception not matched by an `except*` block is automatically repacked into a smaller `ExceptionGroup` and propagated upward 🚀. --- ### Interactive Pop-Quiz 🧠 #### What is the primary purpose of the `except*` syntax introduced in Python 3.11? - [ ] To selectively catch and handle specific sub-exceptions bundled inside an `ExceptionGroup` 💥 - [ ] To catch wildcards and regular expression errors from string patterns - [ ] To catch exceptions raised across separate multi-machine clusters - [ ] To suppress all exceptions without running finally blocks --- ### Practical Challenge 🎯 Within an `asyncio.TaskGroup`, trigger two tasks: one raising `ValueError('Bad value')` and one raising `TypeError('Bad type')`. Wrap the group in `try/except*` blocks, append the exception type names to a list `errors`, and print `sorted(errors)`. <details> <summary>Solution</summary> ```python import asyncio async def fail_val(): raise ValueError("Bad value") async def fail_typ(): raise TypeError("Bad type") async def main(): errors = [] try: async with asyncio.TaskGroup() as tg: tg.create_task(fail_val()) tg.create_task(fail_typ()) except* ValueError: errors.append("ValueError") except* TypeError: errors.append("TypeError") print(sorted(errors)) asyncio.run(main()) ``` </details>