[EMAIL PROTECTED] wrote: > O/S: Windows XP Service Pack 2 > Python version: 2.4 > > Unable to understand how to build a class to handle an exception. > > Contents of sample01.py: > import exceptions > class SampleMain: > try: > def __init__(self): > print 'in SampleMain constructor' > > def Allowed(self): > print 'in allowed' > > def NotYetAllowed(self): > UCError = UnderConstructionError('not yet ready') > raise UCError > > except UnderConstructionError, e: > print e.msg > > class Error(exceptions.Exception): > def __init__(self): > print 'in base class constructor' > > class UnderConstructionError(Error): > def __init__(self, message): > print 'in UnderConstructionError constructor' > self.msg = message > > Copy/paste of interactive window: > PythonWin 2.4 (#60, Nov 30 2004, 09:34:21) [MSC v.1310 32 bit (Intel)] > on win32. > Portions Copyright 1994-2004 Mark Hammond ([EMAIL PROTECTED]) - > see 'Help/About PythonWin' for further copyright information. > >>> import sample01 > >>> x = sample01.SampleMain() > in SampleMain constructor > >>> x.NotYetAllowed() > in UnderConstructionError constructor > Traceback (most recent call last): > File "<interactive input>", line 1, in ? > File "C:\Python24\sample01.py", line 12, in NotYetAllowed > raise UCError > UnderConstructionError: <unprintable instance object> > >>> > > My questions are: > 1) What is causing the error described in the Traceback? > 2) Given that what I want to happen when the NotYetAllowed() method is > called is: > a) an exception to be raised > b) the exception results in a message getting printed; the message > should come from the place where the exception was raised, and it > should be passed to the exception class as a string object; so in this > case the message that should be printed is 'not yet ready' > c) the exception gets handled with the try/except within the > SampleMain class > > My question is: what changes must I make to the code to make that > happen? > > Thank you. Hello , This is originally snagged from the standard library. Spend time reading thru the modules they will show you how to do a lot of things. # Exception example class PSCError(Exception): # Base for custom errors def __init__(self, msg=''): self._msg = msg Exception.__init__(self, msg) def __repr__(self): return self._msg __str__ = __repr__
class PathError(PSCError): def __init__(self, msg): PSCError.__init__(self, 'Path error! : %s'% msg) class InputError(PSCError): def __init__(self, msg): PSCError.__init__(self, 'Input error! : %s'% msg) # and you use it like this raise PathError, 'Please check path' raise InputError, 'Improper input try again' hth, M.E.Farmer -- http://mail.python.org/mailman/listinfo/python-list