How asyncio works? and event loop vs exceptions

Ian Kelly ian.g.kelly at gmail.com
Sat Jul 23 10:06:31 EDT 2016


On Fri, Jul 22, 2016 at 6:27 PM, Marco S. via Python-list
<python-list at python.org> wrote:
> Furthermore I have a question about exceptions in asyncio. If I
> understand well how it works, tasks exceptions can be caught only if
> you wait for task completion, with yield from, await or
> loop.run_until_complete(future). But in this case the coroutine blocks
> the execution of the program until it returns. On the contrary you can
> execute the coroutine inside an asyncio task and it will be
> non-blocking, but in this case exceptions can't be caught in a try
> statement.

If you don't want to block the current function on the task, then spin
off another task to do the error handling.  Instead of this:

async def do_something():
    try:
        await do_something_else()
    except DidNothingError as e:
        handle_error(e)
    ...

Consider this:

async def do_something():
    get_event_loop().create_task(await_and_handle(do_something_else()))
    ...

async def await_and_handle(awaitable):
    try:
        await awaitable
    except DidNothingError as e:
        handle_error(e)

If you want, you could generalize that further by passing in the
exception class and error handler as well:

async def do_something():
    get_event_loop().create_task(await_and_handle(
        do_something_else(), DidNothingError, handle_error))
    ...

async def await_and_handle(awaitable, error_class, handler):
    try:
        await awaitable
    except error_class as e:
        handler(e)



More information about the Python-list mailing list