异常链接仅在Python 3中可用,您可以在其中编写:
try:
v = {}['a']
except KeyError as e:
raise ValueError('Failed') from e
产生像
Traceback (most recent call last):
File "t.py", line 2, in <module>
v = {}['a']
KeyError: 'a'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "t.py", line 4, in <module>
raise ValueError('Failed') from e
ValueError: Failed
在大多数情况下,您甚至都不需要from
; 默认情况下,Python 3将显示异常处理期间发生的所有异常,如下所示:
Traceback (most recent call last):
File "t.py", line 2, in <module>
v = {}['a']
KeyError: 'a'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "t.py", line 4, in <module>
raise ValueError('Failed')
ValueError: Failed
class MyError(Exception):
def __init__(self, message, cause):
super(MyError, self).__init__(message + u', caused by ' + repr(cause))
self.cause = cause
try:
v = {}['a']
except KeyError as e:
raise MyError('Failed', e)