Which exception to use?

Ben Caradoc-Davies ben at wintersun.org
Tue Jan 28 17:49:38 EST 2003


On Tue, 28 Jan 2003 14:39:01 -0500, Edward C. Jones <edcjones at erols.com> 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'

My favourite in these circumstances is AssertionError. You can even rewrite
them using the assert keyword.

assert len(sys.argv) == 2, 'program requires exactly one argument'

assert len(sometuple) == 3, 'sometuple must have length 3'

You can suppress the stack trace by handling the exception and printing just
the detail. This is quite useful for checking program arguments, when you want
users to get a nicely formatted error message.

try:
    args = read_args()  # parse the command-line args, checked with assert
except AssertionError, detail:
    print >>sys.stderr, detail
    sys.exit(1)

-- 
Ben Caradoc-Davies <ben at wintersun.org>
http://wintersun.org/
Imprisonment on arrival is the authentic Australian immigration experience.




More information about the Python-list mailing list