How to get inner exception traceback

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Apr 25 00:07:56 EDT 2008


En Thu, 24 Apr 2008 08:20:29 -0300, Thomas Guettler <hv at tbz-pariv.de>  
escribió:

> How can you get the traceback of the inner exception?
>
> try:
>      try:
>          import does_not_exit
>      except ImportError:
>          raise Exception("something wrong")
> except:
>      ...
>
>
> Background: In Django some exceptions are caught and a new
> exception gets raised. Unfortunately the real error is hard
> to find. Sometimes I help myself and change (in this example)
> ImportError to e.g. IOError and then I can see the real root
> of the problem. But maybe there is a way to get the inner
> exception and its traceback. This could be displayed in the
> debug view.

You already got a couple ways to do it - but I'd ask why do you want to  
mask the original exception? If you don't have anything valuable to do  
with it, just don't catch it. Or raise the *same* exception+context,  
perhaps after modifying it a bit:

try:
   try:
     import does_not_exist
   except ImportError, e:
     e.args = ("Something is wrong with the plugin system\nDetails: %s" %  
e.args,)
     raise # <-- note the "bare" raise
except:
   import traceback
   print "An error has occurred"
   print sys.exc_info()[1]
   print sys.exc_info()[0].__name__
   traceback.print_tb(sys.exc_info()[2])
   # or whatever you want to do with the exception

-- 
Gabriel Genellina




More information about the Python-list mailing list