异常链接仅在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 evalueError: 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您可以在 Python 2中执行的操作 是向您的异常类添加自定义属性,例如:
class MyError(Exception): def __init__(self, message, cause): super(MyError, self).__init__(message + u', caused by ' + repr(cause)) self.cause = causetry: v = {}['a']except KeyError as e: raise MyError('failed', e)


