New style classes as exceptions (Was: exception handing)

Steve Holden sholden at holdenweb.com
Mon Jul 1 13:02:03 EDT 2002


"Jonathan Hogg" <jonathan at onegoodidea.com> wrote in message
news:B946351B.D405%jonathan at onegoodidea.com...
> On 1/7/2002 14:57, in article
> mailman.1025531942.11729.python-list at python.org, "Mark McEahern"
> <marklists at mceahern.com> wrote:
>
> >> New style classes don't work when used as exceptions.  I guess it
> >> should be considered as a bug.
> >
> > Just out of curiousity:  How come you aren't subclassing from Exception?
>
> The language doesn't require anyone to. You can throw an instance of any
old
> class:
>
> >>>> class Foo: pass
> > ...
> >>>> raise Foo()
> > Traceback (most recent call last):
> > File "<stdin>", line 1, in ?
> > __main__.Foo: <__main__.Foo instance at 0x3f7aa8>
> >>>>
>
That's well known, but it certainly isn't good style.

> Besides which, it doesn't work even if you do:
>
> >>> class FooError( StandardError, object ):
> ...     pass
> ...
> >>> raise FooError()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: exceptions must be strings, classes, or instances, not FooError
> >>>
>
I fail to see how the example above claims to "subclass from Exception". It
certainly doesn't seem to be a very good idea to use object as one of the
bases, since this is *known* to cause problems. Instead see, for example:

>>> class MyError(IOError):
...     pass
...
>>> raise MyError
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
__main__.MyError
>>> raise MyError("Hooray!")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
__main__.MyError: Hooray!
>>>

> The problem is that only pure instances of old-style classes can be
thrown.
> This bit me too when I was doing the above - mixing in a new-style class
> with an exception.
>
> I'd consider this a bug too, but I haven't bothered checking Sourceforge
to
> see if anyone else has already.
>
I think it's currently a feature, but it will doubtless become a bug if this
situation continues for too long...

regards
-----------------------------------------------------------------------
Steve Holden                                 http://www.holdenweb.com/
Python Web Programming                http://pydish.holdenweb.com/pwp/
-----------------------------------------------------------------------








More information about the Python-list mailing list