Re-raise different exception with original stack trace
MRAB
python at mrabarnett.plus.com
Fri Oct 14 18:49:53 EDT 2011
On 14/10/2011 22:30, Prasad, Ramit wrote:
> Hi all,
> Hopefully you guys can help me with my problem.
>
> Basically I have a UI program that can "save" information. The UI passes the save to the controller and the controller saves a file and does some post processing. If saving the file fails, I want to handle the error differently than if the error was in post processing. In both cases the possible exceptions are varied and unknown so I cannot pick and choose certain exception. The problem with the sample program below is that the stack trace is replaced by the re-raise. What would be the best way(s) to get the original stack trace in save_from_UI if the exception occurs in post_process? Using Python 2.6 and Windows(XP and 7) / Linux.
>
> Def save_from_model():
> save() # do not catch exception (could be any exception)
> try:
> post_process()
> except Exception as e:
> #do something
> raise CustomException() # "wrap" exception so bar knows to handle it differently
>
> def save_from_UI():
> try:
> foo()
> except CustomException() as e:
> # How do I get the original stacktrace instead of the reraise?
> except Exception as e:
> # do something else with this exception
>
You could save a reference to the exception in the custom exception:
class CustomException(Exception):
def __init__(self, e):
Exception.__init__(self)
self.exc = e
def save_from_model():
save() # do not catch exception (could be any exception)
try:
post_process()
except Exception as e:
#do something
raise CustomException(e)
def save_from_UI():
try:
foo()
except CustomException as e:
# Original exception is e.exc
except Exception as e:
# do something else with this exception
More information about the Python-list
mailing list