Middle
What happens in asyncio.gather() if one of the tasks raises an error? How can you prevent exceptions from being lost?
sobes.tech AI
Answer from AI
If an exception occurs in one of the tasks passed to asyncio.gather(), by default gather interrupts execution and immediately raises that exception. The other tasks may be canceled, and their results will not be returned.
To prevent exceptions from being lost and to be able to get the results of all tasks along with error information, you can use the return_exceptions=True parameter. In this case, gather will return a list of results, where instead of an exception, the exception object itself will be present, which can be handled separately.
Example:
import asyncio
async def task(n):
if n == 2:
raise ValueError("Error in task 2")
return n * 2
async def main():
results = await asyncio.gather(
task(1),
task(2),
task(3),
return_exceptions=True
)
for i, result in enumerate(results, 1):
if isinstance(result, Exception):
print(f"Task {i} finished with an error: {result}")
else:
print(f"Task {i} returned result: {result}")
asyncio.run(main())
Thus, return_exceptions=True allows you not to lose exceptions and handle them after all tasks are completed.