My first Python program

Chris Torek nospam at torek.net
Wed Oct 13 14:26:24 EDT 2010


In article <slrnibboof.29uv.usenet-nospam at guild.seebs.net>
Seebs  <usenet-nospam at seebs.net> wrote:
>> * raising `Exception` rather than a subclass of it is uncommon.
>
>Okay.  I did that as a quick fix when, finally having hit one of them,
>I found out that 'raise "Error message"' didn't work.  :)  I'm a bit unsure
>as to how to pick the right subclass, though.

For exceptions, you have two choices:

  - pick some existing exception that seems to make sense, or
  - define your own.

The obvious cases for the former are things like ValueError or
IndexError.  Indeed, in many cases, you just let a work-step
raise these naturally:

    def frobulate(self, x):
        ...
        self.table[x] += ...   # raises IndexError when x out of range
        ...

For the latter, make a class that inherits from Exception.  In
a whole lot of cases a trivial/empty class suffices:

    class SoLongAndThanksForAllTheFish(Exception):
        pass

    def ...:
        ...
        if somecondition:
            raise SoLongAndThanksForAllTheFish()

Since Exception provides a base __init__() function, you can
include a string:

            raise SoLongAndThanksForAllTheFish('RIP DNA')

which becomes the .message field:

    >>> x = SoLongAndThanksForAllTheFish('RIP DNA')
    >>> x.message
    'RIP DNA'
-- 
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W)  +1 801 277 2603
email: gmail (figure it out)      http://web.torek.net/torek/index.html



More information about the Python-list mailing list