Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

asyncio.CancelledError

Signals cancellation at an await point so a coroutine can clean up before propagating cancellation.

Version: Python 3.14; repository image, production runtime not attested

Syntax

except asyncio.CancelledError:

Signals cancellation at an await point so a coroutine can clean up before propagating cancellation.

It inherits directly from BaseException. Catch it explicitly when observing a cancelled task.

Task.cancel requests interruption; the exception is normally injected at the next opportunity for the task to resume. CancelledError inherits BaseException so except Exception skips it. Run cleanup in finally and normally re-raise if caught. The task reports cancelled() only once cancellation propagates out; in the example awaiting it observes that state. Suppressing the exception does not reset cancelling(). To clear the cancellation state deliberately, uncancel() subtracts one outstanding request.

import asyncio
async def main():
    cleaned = []
    async def worker():
        try:
            await asyncio.Event().wait()
        finally:
            cleaned.append(True)
    t = asyncio.create_task(worker())
    await asyncio.sleep(0)
    t.cancel()
    try:
        await t
    except asyncio.CancelledError:
        assert t.cancelled() and cleaned == [True]
    assert not issubclass(asyncio.CancelledError, Exception)
asyncio.run(main())
import asyncio
async def main():
    t = asyncio.current_task()
    t.cancel()
    try:
        await asyncio.sleep(0)
    except asyncio.CancelledError:
        assert t.cancelling() == 1 and t.uncancel() == 0
asyncio.run(main())

Examples

import asyncio

async def main():
    task = asyncio.create_task(asyncio.sleep(60))
    await asyncio.sleep(0)
    task.cancel()
    try:
        await task
    except asyncio.CancelledError:
        print(task.cancelled())

asyncio.run(main())

Result

True

Task.cancel requests interruption; the exception is normally injected at the next opportunity for the task to resume. CancelledError inherits BaseException so except Exception skips it. Run cleanup in finally and normally re-raise if caught. The task reports cancelled() only once cancellation propagates out; in the example awaiting it observes that state. Suppressing the exception does not reset cancelling(). To clear the cancellation state deliberately, uncancel() subtracts one outstanding request.

Sources