message of Exception

Chris Rebert clp2 at rebertia.com
Tue Jan 6 22:09:17 EST 2009


On Tue, Jan 6, 2009 at 6:56 PM, Steven Woody <narkewoody at gmail.com> wrote:
> Hi,
>
> I am trying define an Exception as below:
>
> class MyError(Exception):
>    def __init__(self, message):
>        self.message = message
>
> And, I expect that when I raise a MyError as
>    raise MyError, "my message"
> the python should print a line such as
>   MyError: my message
>
> But I did not get that, I just got:
>   ...
>   MyError
>
> I guess I had made something wrong with the __init__() definition, but
> I can not find an answer in doc.  Please help, thanks!

You need to call the superclass constructor:

#note: this code will be different in Py 3.0
class MyError(Exception):
    def __init__(self, message):
        super(MyError, self).__init__(message)

Or if you're not going to add anything else to MyError, you might as
well just leave the class body empty and it'll use Exception's
__init__, which takes care of the message.

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list