subclassing Exceptions

Volucris volucris at hotmail.com
Sun Jul 22 01:51:31 EDT 2001


If all you want is your own exception (nothing fancy), all you need is a
class:

class SpamException:
    pass

you can raise and catch that just like any exception, but it'll be kind of
ugly when it gets printed.

class SpamException:
    def __str__(self):
        return "cooking spam is not required"

that will give a clue as to what the exception means. That said, I don't
recall ever seeing an exception not subclassed from Exception, so it's
probably a good idea.

class SpamException(Exception):
    def __str__(self):
        return "cooking spam is not required"

I don't know why every one is subclassed, but the HPIC seem to know what
they're doing so far. I have no reason to question them. Yet.

--

Volucris (a) hotmail.com
"Eu não falo uma única palavra do português."

"Sheila King" <sheila at spamcop.net> wrote in message
news:9ihklt8u0vvh1aa0mg6tadbmjo9mot47e0 at 4ax.com...
> OK, I've become fairly comfortable with defining my own classes and
> subclassing other classes and so on...
>
> Now I'm wanting to create some of my own exceptions. I've searched
> comp.lang.python at Google Groups, and the archives for the Tutor list,
> and faqts.python.com and my copy of Core Python Programming, but all I
> find on the subject is essentially this:
>
> """
>
> You can create a new exception by subclassing one of the standard
> exceptions like this:
>
> class MyNewException(SomeStandardException):
>     pass
>
>
> Just use the 'pass' statement unless you want to override some of the
> methods/data of the Standard Exception.
>
> """
>
> And that's all the information I can find.
>
> I tried looking under the /Python20 directory for source or something
> for the Exception classes, but can't find it. For example, right now I'm
> working on subclassing the rfc822.py module, and I found the file
> rfc822.py in /Python20/Lib and studied the source until I understood it,
> and could subclass it. I'd like to find something similar for the
> standard exception classes. I looked in the /include directory and some
> others but can't find what I'm needing.
>
> Thanks for any pointers/tips.
>
> --
> Sheila King
> http://www.thinkspot.net/sheila/
> http://www.k12groups.org/
>
>





More information about the Python-list mailing list