如果你足够幸运只支持python 3。X,这真的变成了一件美丽的事情:)
提高从
我们可以使用raise from链接异常。
try:
1 / 0
except ZeroDivisionError as e:
raise Exception('Smelly socks') from e
在这种情况下,调用者将捕获的异常具有引发异常的位置的行号。
Traceback (most recent call last):
File "test.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 "test.py", line 4, in <module>
raise Exception('Smelly socks') from e
Exception: Smelly socks
注意,底部异常只有我们引发异常的堆栈跟踪。调用者仍然可以通过访问他们捕获的异常的__cause__属性来获得原始异常。
with_traceback
或者你可以使用with_traceback。
try:
1 / 0
except ZeroDivisionError as e:
raise Exception('Smelly socks').with_traceback(e.__traceback__)
使用这种形式,调用者将捕获的异常具有原始错误发生位置的回溯。
Traceback (most recent call last):
File "test.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 "test.py", line 4, in <module>
raise Exception('Smelly socks').with_traceback(e.__traceback__)
File "test.py", line 2, in <module>
1 / 0
Exception: Smelly socks
注意,底部的异常中有执行无效除法的行,也有重新引发异常的行。