Python "During handling of the above exception, another exception occurred" 解释

During handling of the above exception, another exception occurred

产生原因:处理异常时,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

The above exception was the direct cause of the following exception

产生原因:处理异常时,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
posted @ 2025-03-31 14:35  Undefined443  阅读(284)  评论(0)    收藏  举报