Hi

Please take a look at

class ShortInputException(Exception):       #QUESTION: Why do I have to inherit from the "Exception" class?
    def __init__(self, length, atleast):
        Exception.__init__(self)            #QUESTION: Why do I have to add this?
        self.length = length
        self.atleast = atleast


try:
    s = raw_input('Enter something --> ')
    if len(s) < 3:
        raise ShortInputException(len(s), 3)
except EOFError, object_EOF:                   #QUESTION: How do I find the data variables of object_EOF?
    print '\nWhy did you do an EOF on me?'
except ShortInputException, object_SIE:
    print 'ShortInputException: The input was of length %d, \
    was expecting at least %d' % (object_SIE.length, object_SIE.atleast)

Ok, so I have three questions, both shown in the above code. I have the above example from "Byte of Python":

1) Why do I have to inherit from the exception-class in order to create my own exceptions? I mean, what parameters are inherited that I cannot create myself?
2) Why do I have to call the constructor of the Exception class?
3) I have included the saving of the error object in object_EOF, but how do I find out what data/methods object_EOF contains?


Thanks.

Best,
Niles.

Recommended Answers

All 2 Replies

Member Avatar for Enalicho

Ugh. Your questions are very awkward, hence why you have no answers.

Try reading this -
http://docs.python.org/tutorial/errors.html

1) From http://docs.python.org/tutorial/errors.html#raising-exceptions, "The sole argument to raise indicates the exception to be raised. This must be either an exception instance or an exception class (a class that derives from Exception)."
So that's why it needs to be - for raise to work.

2) You don't. You can override it if you want.

3) This is poorly documented. Use dir() to play around, and have a look here - http://docs.python.org/library/exceptions.html and here - http://docs.python.org/tutorial/errors.html#handling-exceptions
Basically, it has args and message that you should play with.

"Ugh. Your questions are very awkward, hence why you have no answers." Haha, thanks (I guess?) :-)

Thanks for the help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.