如何在 Python 中引发其他错误并将原因保留在堆栈跟踪中?
How to raise additional error in Python and keep cause in stack trace?
我写了
try:
...
except Exception as e:
raise ValueError(e, "Was unable to extract date from filename '%s'" % filename)
现在,当 try
块内发生异常时,我会丢失有关它的信息。我打印了堆栈跟踪,我只看到带有 raise
语句的行号,没有关于实际 e
发生位置的信息。
如何修复?
使用raise exc from another_exc
:
try:
...
except Exception as e:
raise ValueError("Was unable to extract date from filename '%s'" % filename) from e
添加 from e
将确保有两个回溯由 连接,上述异常是以下异常的直接原因".
我写了
try:
...
except Exception as e:
raise ValueError(e, "Was unable to extract date from filename '%s'" % filename)
现在,当 try
块内发生异常时,我会丢失有关它的信息。我打印了堆栈跟踪,我只看到带有 raise
语句的行号,没有关于实际 e
发生位置的信息。
如何修复?
使用raise exc from another_exc
:
try:
...
except Exception as e:
raise ValueError("Was unable to extract date from filename '%s'" % filename) from e
添加 from e
将确保有两个回溯由 连接,上述异常是以下异常的直接原因".