Senior LevelPython
How do ExceptionGroups and except* (PEP 654) handle multiple concurrent exceptions in Python 3.11+?
❓ Interview Prompt: Explain `ExceptionGroup`, `except*` syntax, handling multiple concurrent exceptions, and filtering exception types.
When running concurrent tasks in parallel, multiple independent coroutines can raise exceptions simultaneously. Python 3.11 (PEP 654) introduces 'ExceptionGroup' and *'except'**:
The 'except*' Syntax:
Allows catching and handling specific exception types inside an 'ExceptionGroup' concurrently without unrolling the entire group!
Code Implementation Example
python
import asyncio
async def bad_task1():
raise ValueError('Invalid Value')
async def bad_task2():
raise TypeError('Invalid Type')
async def main():
try:
async with asyncio.TaskGroup() as tg:
tg.create_task(bad_task1())
tg.create_task(bad_task2())
except* ValueError as eg:
print('Handled ValueErrors:', eg.exceptions)
except* TypeError as eg:
print('Handled TypeErrors:', eg.exceptions)
asyncio.run(main())💡Catching multiple concurrent exception types using except* in Python 3.11+.
🎯 Interview Key Takeaway
Use except* in Python 3.11+ to handle specific exception types inside concurrent ExceptionGroups cleanly.
#ExceptionGroup#except*#Python 3.11#PEP 654#Senior
Back to all Python Questions→