Skip to content
The Chat Archive
gpt-4o-2024-08-06· OpenAI WildChat-4.8M (AI2)

asyncio.gather(*tasks) how to continue if one tasks errors

  1. User

    asyncio.gather(*tasks) how to continue if one tasks errors

  2. Assistant

    When you're using asyncio.gather(*tasks), it will raise an Exception as soon as one of the tasks it manages raises an exception. If you want to continue running the other tasks even if one of them raises an exception, you can use the return_exceptions=True keyword argument. This will allow gather to return a list of results or exceptions without stopping the execution of other tasks.

    Here's an example illustrating how to use it:

    import asyncio
    
    async def task1():
        await asyncio.sleep(1)
        print("Task 1 completed")
        return "Result from task 1"
    
    async def task2():
        await asyncio.sleep(2)
        print("Task 2 completed")
        raise ValueError("An error occurred in task 2")
    
    async def task3():
        await asyncio.sleep(1)
        print("Task 3 completed")
        return "Result from task 3"
    
    async def main():
        tasks = [task1(), task2(), task3()]
        results = await asyncio.gather(*tasks, return_exceptions=True)
    
        for i, result in enumerate(results):
            if isinstance(result, Exception):
                print(f"Task {i+1} raised an exception: {result}")
            else:
                print(f"Task {i+1} returned: {result}")
    
    asyncio.run(main())
    

    In this example, even though task2 raises an exception, task1 and task3 will complete successfully. The output will contain the error from task2 and the results from the tasks that didn't fail.