`__cause__` 和 `__context__` 在异常链中有什么不同?它们的优先级是如何确定的?

在 Python 的异常处理中,`__cause__` 和 `__context__` 都与异常链(exception chaining)相关,但它们的用途和优先级有所不同。以下是详细说明:

### 1. `__cause__` 和 `__context__` 的区别

#### `__cause__`
- 通过 `raise ... from ...` 语法显式设置。
- 表示当前异常是由另一个异常直接引发的。
- 用于表明明确的因果关系。

**示例:**
```python
try:
   1 / 0
except ZeroDivisionError as e:
   raise ValueError("Invalid operation") from e

运行后会输出:

ValueError: Invalid operation

The above exception was the direct cause of the following exception:

ZeroDivisionError: division by zero

__context__

  • 当在一个异常的上下文中引发另一个异常时,Python 会自动设置 __context__。
  • 表示当前异常是在处理另一个异常时发生的,但两者之间没有明确的因果关系,更多是一种上下文关系。

示例:

try:
   1 / 0
except ZeroDivisionError:
   raise ValueError("Invalid operation")

运行后会输出:

ValueError: Invalid operation

During handling of the above exception, another exception occurred:

ZeroDivisionError: division by zero

2. 优先级

  • Python 优先显示 __cause__ 而非 __context__。
  • 如果 __cause__ 存在,则忽略 __context__。
  • 如果 __cause__ 为 None,则显示 __context__。

示例说明优先级:

try:
   1 / 0
except ZeroDivisionError as e:
   try:
      2 / 0
   except ZeroDivisionError as f:
      raise ValueError("Nested error") from e

这里 ValueError 的 __cause__ 是第一个 ZeroDivisionError,而 __context__ 是第二个 ZeroDivisionError。但优先级规则仅会显示 __cause__。

输出:

ValueError: Nested error

The above exception was the direct cause of the following exception:

ZeroDivisionError: division by zero

附加说明

  • 可以通过设置 raise ... from None 来消除异常的上下文信息。
  • traceback 模块在生成异常回溯时会优先检查 __cause__,然后再检查 __context__。

总结来说,__cause__ 用于明确的因果关系(由 from 语法指定),而 __context__ 用于自动捕获的上下文关系。优先级上,__cause__ 会覆盖 __context__。