Python。从多个异常中引发异常

c z*_*c z 5 python error-handling exception raise python-3.x

我可以引发from另一个异常以提供附加信息,例如:

try:
    age = int(x)
except Exception as ex:
    raise ValueError("{} is not a valid age.".format(x)) from ex
Run Code Online (Sandbox Code Playgroud)

有没有办法从多个异常中获取来源?例如

try:
    age = int(x)
except Exception as ex1:
    try:
        age = date_now().year - parse_date(x).year
    except Exception as ex2:
        raise ValueError("{} is not a valid age or date.".format(x)) from ex1 + ex2
Run Code Online (Sandbox Code Playgroud)

blh*_*ing 0

根据PEP 344 \xe2\x80\x93 Exception的规范,导致当前正在处理的异常的早期异常存储在当前异常对象的属性中,而在语句中__context__显式指定的异常则存储为该属性链接和嵌入式回溯fromraise__cause__

\n
\n

对于显式链接的异常,此 PEP 建议__cause__\n 因为其特定含义。对于隐式链接的异常,\n此 PEP 提议使用该名称,__context__\n因为其预期含义\n比时间优先级更具体,但比\n原因不太具体:一个异常在处理另一个异常的上下文中\n发生。

\n
\n

__cause____context__在回溯报告中正确格式化,因此以下代码:

\n
from datetime import datetime\n \nx = \'foo\'\ntry:\n    age = int(x)\nexcept ValueError:\n    try:\n        age = datetime.now().year - datetime.fromisoformat(x).year\n    except ValueError as e:\n        raise ValueError(f\'{x} is not a valid age or date.\') from e\n
Run Code Online (Sandbox Code Playgroud)\n

将产生以下回溯,并正确注明所有异常源:

\n
Traceback (most recent call last):\n  File "./prog.py", line 5, in <module>\nValueError: invalid literal for int() with base 10: \'foo\'\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n  File "./prog.py", line 8, in <module>\nValueError: Invalid isoformat string: \'foo\'\n\nThe above exception was the direct cause of the following exception:\n\nTraceback (most recent call last):\n  File "./prog.py", line 10, in <module>\nValueError: foo is not a valid age or date.\n
Run Code Online (Sandbox Code Playgroud)\n

演示: https: //ideone.com/icdd8K

\n