Deeper tracebacks?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Dec 11 19:33:08 CET 2008


En Thu, 11 Dec 2008 07:49:42 -0200, R. Bernstein <rocky at panix.com>  
escribió:
> brooklineTom <BrooklineTom at gmail.com> 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."""
     int(3).zork()

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

SomeClass().perform_("error")

output:

Using traceback.print_tb:
   File "test_tb.py", line 11, in perform_
     answer = aMethod()
   File "test_tb.py", line 6, in error
     int(3).zork()
Using traceback.print_exception:
Traceback (most recent call last):
   File "test_tb.py", line 11, in perform_
     answer = aMethod()
   File "test_tb.py", line 6, in error
     int(3).zork()
AttributeError: 'int' object has no attribute 'zork'
Using traceback.extract_tb:
[('test_tb.py', 11, 'perform_', 'answer = aMethod()'), ('test_tb.py', 6,  
'error'
, '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