Exception handling#
Exception handling mostly works as expected from traditional code as well. Note however, that the exceptions only occur when the code is actually executed.
This function will definitely fail on execution
async def i_will_fail(wait_for):
await asyncio.sleep(wait_for)
1/0
return wait_for
There is no problem when creating the coroutine, as the function is not executed yet.
coro = i_will_fail(1)
If the code get executed though …
try:
await coro
except ZeroDivisionError as e:
print(f"Caught that expected error. Message was {e}")
Caught that expected error. Message was division by zero
… the exeception happens.
Same for tasks …
coro = i_will_fail(1)
try:
task = asyncio.create_task(coro)
await task
except ZeroDivisionError as e:
print(f"Caught that expected error. Message was {e}")
Caught that expected error. Message was division by zero
The task is still available though and can be checked upon.
print(f"{task.done()=}")
print(f"{task.exception()=}")
task.done()=True
task.exception()=ZeroDivisionError('division by zero')