Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

TimeoutError / asyncio.TimeoutError — exceeding a time limit

TimeoutError signals that an operation exceeded its time limit. In Python 3.14, asyncio.TimeoutError is a deprecated alias of the same class, not a separate exception. Catch TimeoutError and distinguish a timeout from ordinary task cancellation.

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

Syntax

try:
    async with asyncio.timeout(seconds):
        await operation()
except TimeoutError:
    ...

The built-in TimeoutError is a subclass of OSError; for system functions, it corresponds to errno.ETIMEDOUT. The timeout mechanisms in asyncio also use it. An operation taking a long time does not automatically raise this exception: a limit must come from the API or its configuration.

Since Python 3.11, asyncio.TimeoutError has been a deprecated alias of the built-in TimeoutError. In Python 3.14, asyncio.TimeoutError is TimeoutError evaluates to True. Use except TimeoutError: in new code; you do not need two handlers for these names.

asyncio.timeout(seconds) cancels the current task when its limit expires and transforms the resulting asyncio.CancelledError into TimeoutError when the context exits. Put the handling except outside the async with block for this reason. Ordinary task cancellation is a separate case; do not suppress asyncio.CancelledError inside the operation.

When the time limit expires, asyncio.wait_for() requests cancellation of the awaited operation. It waits for cancellation to finish, so the total wait can exceed the specified limit. If the operation ends as a result of that cancellation, asyncio.wait_for() raises TimeoutError. But if the awaited coroutine catches asyncio.CancelledError and returns a value, asyncio.wait_for() returns that value. An exception raised during cancellation can propagate. Catch the exception as close as possible to the operation whose failure you can handle.

Reference identifiers covered by this entry: TimeoutError / asyncio.TimeoutError.

Examples

import asyncio

async def main():
    print(asyncio.TimeoutError is TimeoutError)
    event = asyncio.Event()
    try:
        async with asyncio.timeout(0):
            await event.wait()
    except TimeoutError:
        print("Timed out")

asyncio.run(main())

Result

True
Timed out

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources