Subclassing exceptions
Chris Liechti
cliechti at gmx.net
Fri Jan 4 16:58:55 EST 2002
sag at hydrosphere.com (Sue Giller) wrote in
news:mailman.1010102348.1522.python-list at python.org:
> I am trying to write an exception class that will pass on info from a
> previous exception (if any) along with the currently raised exception.
why do you wanna do this?
i often use:
...
except:
print >>sys.stderr, "Exception in _ComPortThread:"
traceback.print_exc(file=sys.stderr)
to print a tarceback but continue the program.
> Here is the exception class (test case): It wants to append any input
> args to any existing text from an exception.
>
> import exceptions
> class Ex(exceptions.Exception):
> def __init__(self, args=None):
> import sys
> info = sys.exc_info()
> text = ""
> if not info is None: # always get this!
> text = "%s" % str(info[1])
> if args != None:
> text = text + "\n\t" + args
> self.args = text
i don't know how secure is it to get exception info during an exception is
raised... i would leave my fingers of it...
i would process the last exception end then raise the own exception along
with the extracted info.
> Is there some way to write a subclassed exception that allows me to
> pass on the text from the last raised exception (if any) plus my
> subclassed text?
does this work for you:
class MyException(Exception): pass
...
try:
...
except Exception, msg:
raise MyException, msg
...
> This does not happen from the interactive prompt, but will happen
> from a script. You can have a simple script in PythonWin, with just
> the lines:
>
> import sys
> print sys.exc_info()
>
> and get the same results
>
> ('win32ui', 'There is no active view.', <traceback object at
> 0133FF70>)
python win uses python too.. so maybe you see an exception that was
generated in the GUI.
--
Chris <cliechti at gmx.net>
More information about the Python-list
mailing list