Smart help again

wittempj@hotmail.com martin.witte at gmail.com
Tue Apr 12 14:57:23 EDT 2005


I hope a rewrite makes it a bit more clear for you.

The test module is defined below, it contains a simplified Error
object, it resemble the one I use a lot in my own scripting. The test
file generates an error ( A  ZeroDivisionError in method eggs of class
Spam).

-#!/usr/bin/env python

-import test, sys
-
-try:
-    try:
-        class Spam:
-            def eggs(self):
-                return 1/0
-        foo = Spam()
-        foo.eggs()
-    except Exception, e:
-        raise test.Error('%s: %s' % (e.__class__.__name__, e))
-except test.Error, e:
-    print >> sys.stderr, e.__class__.__name__, e

The Error class takes the last exception, and tries to find the
originating method of that exception, by unwinding the stacktrace


-import sys, traceback
-class Error:
-    def __init__(self, arg):
-        tb = sys.exc_info()[2]
-       while 1:
-            if not tb.tb_next:
-                break
-            tb = tb.tb_next
-        stack = []
-        f = tb.tb_frame
-        while f:
-            stack.append(f)
-            f = f.f_back
-
-        error_originator = stack[0]
-
-        (obj, instance) = error_originator.f_locals.items()[0]
-
-        self._str = 'class instance: %s, method: %s raises %s' % \
-                    (instance, \
-                     error_originator.f_code.co_name, \
-                     arg)
-
-    def __repr__(self):
-        return repr(self._str)

Now the output is:


Error 'class instance: <__main__.Spam instance at 0xb7e0444c>, method:
eggs raises ZeroDivisionError: integer division or modulo by zero'

Now you see the class and methos where the exception was raised,
although I admit that it is quite complicated with all the exception
handling




More information about the Python-list mailing list