The exception chain is only available in Python 3, where you can write:
try: v = {}['a'] except KeyError as e: raise ValueError('failed') from e
which gives a similar output
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
In most cases, you do not even need from ; Python 3 by default displays all exceptions that occurred during exception handling, for example:
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
What you can do in Python 2 is adding custom attributes to your exception class, for example:
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)
phihag May 7, '13 at 8:48 2013-05-07 08:48
source share