Which exception to use?

Chad Netzer cnetzer at mail.arc.nasa.gov
Tue Jan 28 21:43:29 CET 2003

On Tuesday 28 January 2003 11:39, Edward C. Jones wrote:
> Which exception is it best to use in the following pieces of code?
> if len(sys.argv) != 2:
>      raise SomeException, 'program requires exactly one argument'
> if len(sometuple) != 3:
>      raise SomeException, 'sometuple must have length 3'
> I use TypeError or ValueError but they don't feel right. I wish there
> was a SizeError or LengthError.

I do things like this for some library functions that I create (I 
welcome discussion about whether it is a good approach)

class ArgumentError( Exception ):

then when arguments to functions are not acceptable:

if some_arg < 0:
    raise ArgumentError, "such-and-such argument must not be negative."

I like distinguishing errors in the use of the API, from errors in the 
implementation (ie. the various built in Exceptions), at least when 
there IS a distinction.

Bjorn Pettersen indicated that printing the error to stderr and exiting 
is one way to go, but it wouldn't be proper for my library function to 
terminate a caller's program (although using the 'warnings' module to 
output the error message is a nice alternative to printing to stderr 
these days.)

Also, Peter Hansen indicated that the following form of exception 
raising is preferred:

    raise ArgumentError("such-and-such argument must not be negative.")

I'd be interested to know what the preferred method is (if any).  I 
think raising the class itself is more intuitive to my mind (rather 
than building an instance to raise).  Is there a preferred style?

Bay Area Python Interest Group - http://www.baypiggies.net/

Chad Netzer
(any opinion expressed is my own and not NASA's or my employer's)

More information about the Python-list mailing list