Sub topic 6
Handling CancelledError and cleaning up safely
This chapter assumes you know Python 3.11 or newer, async/await, try/except/finally, and how to start tasks with asyncio.run and asyncio.create_task. It builds on the previous chapter, where Task.cancel() requests that a task stop.
What CancelledError is
When a task is cancelled, asyncio raises asyncio.CancelledError inside the task at the point where it is suspended on an await. In Python 3.8 and later, CancelledError inherits from BaseException, not Exception. A plain except Exception: therefore does not catch it. This is deliberate. Cancellation is a control signal, not an ordinary failure.
The exception only appears at an await. A task running a long loop with no await cannot be cancelled until it reaches one.
Cleaning up with finally
The safest cleanup tool is finally. It runs whether the task finishes, fails, or is cancelled.
import asyncio
async def worker():
try:
while True:
await asyncio.sleep(0.1)
finally:
print("worker: releasing resources")
async def main():
task = asyncio.create_task(worker())
await asyncio.sleep(0.35)
task.cancel()
try:
await task
except asyncio.CancelledError:
print("worker was cancelled")
asyncio.run(main())The output is:
worker: releasing resources
worker was cancelledThe finally block runs first. Then the CancelledError propagates to whoever awaits the task. Context managers (with and async with) clean up the same way, so prefer them for files, locks, and connections.
Catching it: always re-raise
Sometimes you need to do more than finally allows, such as logging that a cancellation happened. You can catch CancelledError, but you must re-raise it.
import asyncio
async def worker():
try:
await asyncio.sleep(10)
except asyncio.CancelledError:
print("worker: cancellation requested, saving state")
raise
async def main():
task = asyncio.create_task(worker())
await asyncio.sleep(0.1)
task.cancel()
try:
await task
except asyncio.CancelledError:
print("main: task is cancelled:", task.cancelled())
asyncio.run(main())Awaiting during cleanup
Cleanup code often needs await, for example to close a network connection. This works, because the cancellation has already been delivered. The task is not cancelled a second time unless someone calls cancel() again.
import asyncio
async def worker():
try:
await asyncio.sleep(10)
finally:
await asyncio.sleep(0.1) # simulate an async close
print("worker: connection closed")
async def main():
task = asyncio.create_task(worker())
await asyncio.sleep(0.1)
task.cancel()
await asyncio.gather(task, return_exceptions=True)
asyncio.run(main())Keep cleanup short. A second cancel() during an awaiting cleanup interrupts it, and a cleanup that blocks for a long time delays shutdown.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| `except Exception:` to catch cancellation | Cancellation passes through uncaught | Use `finally`, or catch `CancelledError` explicitly |
| Catching `CancelledError` without `raise` | Cancellation is hidden, task looks successful | Always re-raise |
| Long loops with no `await` | Task cannot be cancelled in time | Add `await asyncio.sleep(0)` at safe points |
| Slow, unbounded cleanup | Shutdown hangs | Keep cleanup brief and bounded |
Exercise
A coroutine wraps its body in try: ... except BaseException: log("failed") and never re-raises. What goes wrong when another part of the program cancels it?
Show answer
CancelledError is a BaseException, so the handler catches it and the cancellation is swallowed. The coroutine returns normally instead of ending as cancelled. Code waiting on it, such as a TaskGroup or a timeout, may not stop as expected. The fix is to use finally for cleanup, or to re-raise with raise after logging.