Asyncio provides an asynchronous programming framework in Python that allows you to write non-blocking and efficient I/O code. A key part of any application is properly handling errors and exceptions. When working with asyncio, there are some unique exception handling challenges to be aware of.
The Basics
Most exceptions raised in asyncio asynchronous coroutines and tasks can be handled normally using
import asyncio
async def main():
try:
result = await some_api_call()
except ValueError:
print("Oops, invalid input")
asyncio.run(main())
This will catch a
CancelledError
One special exception to watch out for is
import asyncio
async def main():
task = asyncio.create_task(other_func())
await asyncio.sleep(1)
task.cancel()
try:
await task
except asyncio.CancelledError:
print("Task was cancelled")
asyncio.run(main())
So make sure to catch
Propagating Exceptions
Another common pitfall is exceptions not propagating back properly from tasks. Use
Overall, handling exceptions with asyncio does take some special care. Set up