Recommended exception method for modules?
Grant Edwards
ge at nowhere.none
Thu Oct 5 11:25:20 EDT 2000
In my spare time, I'm working on a Posix serial port class that
hides all the termios/ioctl ugliness. [I'm glad to see that
the TIOCxxxx stuff has been added to the TERMIOS module for
2.0!]
At the moment I'm doing things like:
if not validBaud(r)
raise 'invalid baud rate - '+str(r)
This is obviously the wrong way to do it, since you'd have to
have an except clause for every possible invalid baud rate.
Looking through the 1.52 library modules, I see that most of
them use strings as exception objects, but a few define classes
to be used as exceptions. Smtplib even sub-classes it's
exceptions.
Can somebody point me to a recommendation for the "right" way
for new modules to do exceptions. I've looked at the tutorials
for both 1.52 and 2.0b2 which explain what the options are but
offer no recommendation. If I understand the tutorial and the
library modules I've looked at, there seem to be three basic
methods:
1) a single exception string for the module:
Error = 'PosixSerial.Error'
if not validBaud(r):
raise Error, 'invalid baud rate'
1) a string for each error type:
BaudError = 'PosixSerial - Invalid baud rate'
if not validBaud(r):
raise BaudError,r
2) a single exception class for the module with a value that
defines the error type:
class PosixSerialError(Exception):
[...]
if not validBaud(r):
raise PosixSerialError('invalid baud rate')
3) a class for each type of error with value(s) that further
explain what is wrong:
class PosixSerialBaudError(Exception):
[...]
if not validBaud(r):
raise PosixSerialBaudError(r)
[this last one could be done as a subclass of a general
PosixSerialError class, -- that way somebody can catch
either all of my exceptions or just individual ones.
Right?]
Are these the basic exception schemes in use?
Does anybody care to share their opinion on the relative merits
of these?
--
Grant Edwards grante Yow! Hey!! Let's watch
at the' ELEVATOR go UP and
visi.com DOWN at th' HILTON HOTEL!!
More information about the Python-list
mailing list