I want to achieve something like this:
def foo():
try:
raise IOError('Stuff ')
except:
raise
def bar(arg1):
try:
foo()
except Exception as e:
e.message = e.message + 'happens at %s' % arg1
raise
bar('arg1')
Traceback...
IOError('Stuff Happens at arg1')
But what I get is:
Traceback..
IOError('Stuff')
Any clues as to how to achieve this? How to do it both in Python 2 and 3?
I’d do it like this so changing its type in
foo()won’t require also changing it inbar().Update 1
Here’s a slight modification that preserves the original traceback:
Update 2
For Python 3.x, the code in my first update is syntactically incorrect plus the idea of having a
messageattribute onBaseExceptionwas retracted in a change to PEP 352 on 2012-05-16 (my first update was posted on 2012-03-12). So currently, in Python 3.5.2 anyway, you’d need to do something along these lines to preserve the traceback and not hardcode the type of exception in functionbar(). Also note that there will be the line:in the traceback messages displayed.
Update 3
A commenter asked if there was a way that would work in both Python 2 and 3. Although the answer might seem to be “No” due to the syntax differences, there is a way around that by using a helper function like
reraise()in thesixadd-on module. So, if you’d rather not use the library for some reason, below is a simplified standalone version.Note too, that since the exception is reraised within the
reraise()function, that will appear in whatever traceback is raised, but the final result is what you want.