Reraise exception with modified stack

Scott David Daniels Scott.Daniels at Acm.Org
Thu Jun 23 12:41:18 EDT 2005


Nicolas Fleury wrote:
> Hi,
> I've made a small utility to re-raise an exception with the same stack 
> as before with additional information in it.  Since I want to keep the 
> same exception type and that some types have very specific constructors 
> (which take, for example, more than one parameter), the only safe way I 
> have found to made it is by hacking the str representation:
> 
> 
> import sys
> 
> class ExceptionStr:
>     def __init__(self, content):
>         self.content = content
>         self.infos = []
>     def addinfo(self, info):
>         self.infos.insert(0, info)
>     def __call__(self):
>         return '\n' + '\n'.join(self.infos + [self.content])
> 
> def reraise(exception, additionalInfo):
>     strFunc = getattr(exception, "__str__", None)
>     if not isinstance(strFunc, ExceptionStr):
>         strFunc = ExceptionStr(str(exception))
>         exception.__str__ = strFunc
>     strFunc.addinfo(additionalInfo)
>     raise exception, None, sys.exc_info()[-1]
> 
How about dropping reraise and changing:
           reraise(...)
to:
           addinfo(...)
           raise

Where addinfo looks like:
     def addinfo(exception, additionalInfo):
         strFunc = getattr(exception, "__str__", None)
         if not isinstance(strFunc, ExceptionStr):
             strFunc = ExceptionStr(str(exception))
             exception.__str__ = strFunc
         strFunc.addinfo(additionalInfo)


So you finale would be:
    if __name__ == '__main__':
        def foo():
            raise AttributeError('Test')
        def bar():
            foo()
        try:
            try:
                try:
                    bar()
                except Exception, exception:
                    addinfo(exception, "While doing x:")
                    raise
            except Exception, exception:
                addinfo(exception, "While doing y:")
                raise
        except Exception, exception:
            addinfo(exception, "While doing z:")
            raise

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list