Deeper tracebacks?

Gabriel Genellina gagsl-py2 at
Thu Dec 11 19:33:08 CET 2008

En Thu, 11 Dec 2008 07:49:42 -0200, R. Bernstein <rocky at>  
> brooklineTom <BrooklineTom at> writes:
>> I want my exception handler to report the method that originally
>> raised an exception, at the deepest level in the call-tree. Let give
>> an example.

> extract_stack() without any arguments is getting this from the
> *current frame* which as you noted doesn't have the last exception
> info included which has been popped; variable sys.last_traceback has the  
> frames
> at the time of the exception, I think.
> So in your code try changing:
>              aRawStack = traceback.extract_stack()
> to
>              aRawStack = traceback.extract_stack(sys.last_traceback)

No, last_traceback is the last *printed* traceback in the interactive  
interpreter. Use the third element in sys.exc_info() instead:

import sys, traceback

class SomeClass:
   def error(self):
     """Raises an AttributeError exception."""

   def perform_(self, aSelector):
       aMethod = getattr(self, aSelector)
       answer = aMethod()
     except AttributeError:
       tb = sys.exc_info()[2]
         print "Using traceback.print_tb:"
         print "Using traceback.print_exception:"
         print "Using traceback.extract_tb:"
         print traceback.extract_tb(tb)
         del tb



Using traceback.print_tb:
   File "", line 11, in perform_
     answer = aMethod()
   File "", line 6, in error
Using traceback.print_exception:
Traceback (most recent call last):
   File "", line 11, in perform_
     answer = aMethod()
   File "", line 6, in error
AttributeError: 'int' object has no attribute 'zork'
Using traceback.extract_tb:
[('', 11, 'perform_', 'answer = aMethod()'), ('', 6,  
, 'int(3).zork()')]

(The "3-name form of the except clause" that I menctioned previously only  
exists in my imagination :) )

Gabriel Genellina

More information about the Python-list mailing list