newbie question - exception processing

mirandacascade at yahoo.com mirandacascade at yahoo.com
Sun Feb 20 02:13:32 EST 2005


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 (mhammond at skippinet.com.au) -
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.




More information about the Python-list mailing list