You need to use the returned values from asyncio.wait()
:
import asyncio
class Error(Exception):
pass
@asyncio.coroutine
def main():
try:
done, pending = yield from asyncio.wait([raise_exception()], timeout=1)
assert not pending
future, = done # unpack a set of length one
print(future.result()) # raise an exception or use future.exception()
except Error:
print('got exception', flush=True)
else:
print('no exception', flush=True)
@asyncio.coroutine
def raise_exception(): # normally it is a generator (yield from)
# or it returns a Future
raise Error("message")
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
Output
got exception
The current implementation of asyncio.coroutine
assumes that if a function is not a generator (like in your case) then it returns a Future and thus it should be converted to be a generator therefore calling raise_exception()
doesn't raise an exception because it just creates the generator object (the coroutine).
Then asyncio.wait()
yields it and some equivalent of future.set_exception(exception)
is done.
To avoid the error output that you see; you need to consume the exception either by calling future.result()
or future.exception()
directly.