Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
821 views
in Technique[技术] by (71.8m points)

python - Asyncio: Weirdness of Task exception was never retrieved

Lets assume I have a simple code:

import asyncio


async def exc():
    print(1 / 0)


loop = asyncio.get_event_loop()

loop.create_task(exc())

try:
    loop.run_forever()
except KeyboardInterrupt:
    loop.stop()
    loop.close()

If I run it, I get error message immediately

Task exception was never retrieved
future: <Task finished coro=<exc() done, defined at qq.py:4> exception=ZeroDivisionError('division by zero',)>
Traceback (most recent call last):
  File "qq.py", line 5, in exc
    print(1 / 0)
ZeroDivisionError: division by zero

But, if I change loop.create_task(exc()) to task = loop.create_task(exc())

I'll get the same error message after click ctrl+c

Why does task assignment change the time of output of error?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A Exception in the Task (of underlying asyncio.Future to be precise) can be retrieved with Future.exception(). If it's not retrieved, the exception will be handled at release of the Future object with eventloop's call_exception_handler.

So, as @dirn pointed, while the Task has reference (assigned to variable in your case) it's not going be freed, therefore del task_future won't be called, loop's handler won't be executed either.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...