Python 异常链

Implicit Chaining

产生原因:处理异常时,except 块中的代码抛出新的异常。

示例代码:

try:
    1 / 0  # 这里抛出 ZeroDivisionError
except ZeroDivisionError:
    raise ValueError  # 这里抛出 ValueError
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    1 / 0
    ~~^~~
ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    raise ValueError
    ^^^^^^^^^^^^^^^^
ValueError

Explicit Chaining

产生原因:处理异常时,except 块中的代码抛出新的异常,并通过 raise from 语句指定原始异常。

示例代码:

try:
    1 / 0  # 原始异常
except ZeroDivisionError as e:
    raise ValueError from e  # 新异常
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    1 / 0
    ~~^~~
ZeroDivisionError: division by zero

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

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    raise ValueError from e
    ^^^^^^^^^^^^^^^^^^^^^^^
ValueError

Traceback (most recent call last):
  File "/lib/python3.13/site-packages/urllib3/response.py", line 899, in _error_catcher
    yield
  File "/lib/python3.13/site-packages/urllib3/response.py", line 1045, in _raw_read
    raise IncompleteRead(self._fp_bytes_read, self.length_remaining)
urllib3.exceptions.IncompleteRead: IncompleteRead(1189312193 bytes read, 2637581857 more expected)

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

Traceback (most recent call last):
  File "/lib/python3.13/site-packages/requests/models.py", line 820, in generate
    yield from self.raw.stream(chunk_size, decode_content=True)
  File "/lib/python3.13/site-packages/urllib3/response.py", line 1253, in stream
    data = self.read(amt=amt, decode_content=decode_content)
  File "/lib/python3.13/site-packages/urllib3/response.py", line 1145, in read
    data = self._raw_read(amt)
  File "/lib/python3.13/site-packages/urllib3/response.py", line 1023, in _raw_read
    with self._error_catcher():
         ~~~~~~~~~~~~~~~~~~~^^
  File "/lib/python3.13/contextlib.py", line 162, in __exit__
    self.gen.throw(value)
    ~~~~~~~~~~~~~~^^^^^^^
  File "/lib/python3.13/site-packages/urllib3/response.py", line 923, in _error_catcher
    raise ProtocolError(arg, e) from e
urllib3.exceptions.ProtocolError: ('Connection broken: IncompleteRead(1189312193 bytes read, 2637581857 more expected)', IncompleteRead(1189312193 bytes read, 2637581857 more expected))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/ubuntu/download.py", line 61, in <module>
    download_pretrained_marl()
    ~~~~~~~~~~~~~~~~~~~~~~~~^^
  File "/home/ubuntu/download.py", line 40, in download_pretrained_marl
    for chunk in tqdm(r.iter_content(chunk_size=1024*1024), unit="MB", total=3650):
                 ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/lib/python3.13/site-packages/tqdm/std.py", line 1181, in __iter__
    for obj in iterable:
               ^^^^^^^^
  File "/lib/python3.13/site-packages/requests/models.py", line 822, in generate
    raise ChunkedEncodingError(e)
requests.exceptions.ChunkedEncodingError: ('Connection broken: IncompleteRead(1189312193 bytes read, 2637581857 more expected)', IncompleteRead(1189312193 bytes read, 2637581857 more expected))
IncompleteRead
    ↓ (direct cause)
ProtocolError
    ↓ (rethrow)
ChunkedEncodingError

Python 里的三种关键关系:

机制 表现形式 含义
raise E 单层异常 当前层直接失败
raise E from X The above exception was the direct cause of... 显式因果链
except X: raise Y 最终异常不同 语义包装(rethrow)
posted @ 2025-03-31 14:35  Undefined443  阅读(407)  评论(0)    收藏  举报