[Tutor] subclassing Exceptions

Michael P. Reilly arcege@speakeasy.net
Sun, 22 Jul 2001 07:10:45 -0400 (EDT)


Sheila King wrote
> 
> On Sat, 21 Jul 2001 20:21:34 -0700 (PDT), Danny Yoo
> <dyoo@hkn.eecs.berkeley.edu>  wrote about Re: [Tutor] subclassing
> :    Python/exceptions.c
> :
> :file in the Python source code.  I don't think that it will help, though,
> :in understanding how to subclass exceptions for your own use: it's in C.
> 
> Ah, source code...that doesn't come with the standard Windows install
> .exe version, does it? (It does come with the Unix installs, I'm sure.)
> I probably would have to go to python.org and grab it.
> 
> Do you think it would be that difficult for me to understand the C code?
> (I have taught C++ for the past two years to AP Comp Sci
> students...granted, an Intro level College course...not overly
> in-depth.)

Then you might want to download Python 1.5.2 (binaries or sources).
The exceptions were Python classes, not C classes (or a built-in module
for that matter).  The C code in the exceptions.c file aren't really going
to help you subclass the exceptions in Python.  It will help you if you
ever decide to create C extension classes instead of C extension types.
(There is no direct mechanism in the C API to create a Python class,
only Python types (string, integer, list, etc.).)

For the most part, you usually do not have to override the methods unless
you want to handle the data in a very specific manner.  The Exception
class already handles data in versatile ways.  The subclasses you had
before usually suffice.

If I need/want to make a more complicated structure, then I make a
subclass of Exception, then subclasses from that.  This is a snippet
from my mimecntl module:

# Exceptions
class MimeError(Exception):
  """Signals that an error occured in the operation of the MIME document.
For example, accessing a multipart doc as a file."""

class MimeTypeError(MimeError, TypeError):
  """The MIME document is not correct for the method called."""
class NoRecoding(MimeError):
  """The document was not recoded."""

Raising MimeTypeError could be caught with either "except TypeError" or
"except MimeError" clauses.  All three could be caught just with
MimeError.

It all depends on what your application requires.

  -Arcege

-- 
+----------------------------------+-----------------------------------+
| Michael P. Reilly                | arcege@speakeasy.net              |