Subclassing exceptions
Sue Giller
sag at hydrosphere.com
Thu Jan 3 19:01:27 EST 2002
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.
This is in Windows (win32all 1.40) I am using sys.exc_info() to get
the current state of the exception. According to Beazley, pg 118,
exc_info() should return None if no exception is currently being
handled. See the end of the message for the subclass.
If I catch an exception, and then raise my own Ex exception, things
seem ok: (The following prints "Ex: unsupported operand types for
+; Raising an exception" which is what I want)
try: a = 1 + 'b'
except: raise Ex, "Raising an exception
However, if I just raise my exception, I don't get None back from
exc_info, but rather a win32ui error: There is no active view". The
following prints "Ex: There is no active view.;Raising cain". I would
expect to get None since no exception has been raised before my
exception is raised.
raise Ex, "Raising cain"
A trace on that shows
Traceback (most recent call last):
File "C:\Python21\Pythonwin\pywin\framework\intpyapp.py", line
75, in OnCommand
v = self.GetActiveView() # Raise an exception if none - good -
then we want default handling
win32ui: There is no active view.
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
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?
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>)
More information about the Python-list
mailing list