Build-in or user-defined exceptions?

Peter Hansen peter at engcorp.com
Sat May 14 10:40:32 EDT 2005


Torsten Bronger wrote:
> I write a module, and so I must raise exceptions at several points.
> The PEP 8 says that a module should define their own exceptions base
> class, derived from "Exception", and derivatives of that.
> 
> However, the build-in exceptions cover most of the error types that
> occur in a standard program.  For example, my module communicates
> with measurement instruments, so any communication error would fit
> perfectly to the build-in "IOError", wouldn't it?  

No... *any* communication error?  What if it's an error in the serial 
port layer, or the protocol layer, or the application layer handling 
that communication?  Wouldn't SerialError, ProtocolError, or 
UnrecognizedResponseError (or things like that) be much more readable. 
I find fine-grained app-specific exceptions to be very helpful in 
writing code that talks to machines.

> Invalid arguments
> can raise "TypeError"s, and so on and so forth.

Likewise, RangeError, InvalidAddressError, and the like seem more 
helpful to me, most of the time.

I guess I pretty much follow PEP8 (though I don't recall its details 
right now) since I derive from Exception things like DriverError and 
then derive more specific exceptions from that as needed (in the case of 
a driver module), or ProtocolError and children, etc..

> Is it considered good style to raise build-in exceptions whereever
> one thinks it's appropriate?  Is the definition of module exceptions
> derived from "IOError", "TypeError" etc. a good idea?  Is there some
> sort of style guide for recommended exceptions design in Python?

As Fredrik recommends, use your own judgment, but I believe that one 
should use a very narrow definition for those exceptions.  For example, 
TypeError should be used specifically when the code involved has 
received an object of the wrong type and *not* (for example) when a 
driver receives the wrong "type" of command from another device.

I sometimes derive from things like ValueError (rather than just 
Exception) when it seems appropriate, but that's pretty rare, and it's 
also not what the docs themselves recommend.

Be guided by the descriptions of those exceptions in the docs and not by 
their names alone.  See 
http://docs.python.org/lib/module-exceptions.html for more and be sure 
to read the descriptions of the base classes, not just the subclasses.

-Peter



More information about the Python-list mailing list