{
  "id": "python/asyncio-gather-exception-handling",
  "signature": "asyncio.exceptions.CancelledError: CancelledError not caught in gather",
  "signature_zh": "asyncio 异常：gather 中未捕获 CancelledError",
  "regex": "asyncio\\.exceptions\\.CancelledError:\\ CancelledError\\ not\\ caught\\ in\\ gather",
  "domain": "python",
  "category": "runtime_error",
  "subcategory": null,
  "root_cause": "When using asyncio.gather() with return_exceptions=False (default), an exception in one task cancels others, and CancelledError may propagate unexpectedly.",
  "root_cause_type": "generic",
  "root_cause_zh": "当使用 asyncio.gather() 且 return_exceptions=False（默认）时，一个任务中的异常会取消其他任务，并且 CancelledError 可能意外传播。",
  "versions": [
    {
      "version": "3.8",
      "introduced": null,
      "deprecated": null,
      "removed": null,
      "behavior_change": null,
      "status": "active"
    },
    {
      "version": "3.9",
      "introduced": null,
      "deprecated": null,
      "removed": null,
      "behavior_change": null,
      "status": "active"
    }
  ],
  "os_specific": {},
  "dead_ends": [
    {
      "action": "Wrapping each task in try-except without re-raising",
      "why_fails": "If the task is cancelled externally, CancelledError may still be raised and not caught by a general except.",
      "fail_rate": 0.5,
      "condition": "",
      "sources": []
    },
    {
      "action": "Using asyncio.shield() on all tasks",
      "why_fails": "shield() prevents cancellation but may cause tasks to run indefinitely if not managed.",
      "fail_rate": 0.4,
      "condition": "",
      "sources": []
    }
  ],
  "workarounds": [
    {
      "action": "Use return_exceptions=True to handle exceptions gracefully",
      "success_rate": 0.9,
      "how": "results = await asyncio.gather(task1, task2, return_exceptions=True)\nfor r in results:\n    if isinstance(r, Exception):\n        # handle",
      "condition": "",
      "sources": []
    },
    {
      "action": "Catch CancelledError explicitly in each coroutine",
      "success_rate": 0.85,
      "how": "async def safe_coro():\n    try:\n        await something()\n    except asyncio.CancelledError:\n        # cleanup and re-raise if needed\n        raise",
      "condition": "",
      "sources": []
    }
  ],
  "workarounds_zh": [],
  "transition_graph": {
    "leads_to": [],
    "preceded_by": [],
    "frequently_confused_with": []
  },
  "official_doc_url": null,
  "official_doc_section": null,
  "error_code": null,
  "verification_tier": "ai_generated",
  "confidence": 0.86,
  "fix_success_rate": 0.8,
  "resolvable": "true",
  "first_seen": "2024-08-18",
  "last_confirmed": "2025-01-01",
  "last_updated": "2025-01-01",
  "evidence_count": 0,
  "tags": [],
  "locale": "en",
  "aliases": []
}