Which exception to use?

Erik Max Francis max at alcyone.com
Tue Jan 28 19:26:02 EST 2003


Ben Caradoc-Davies wrote:

> 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'

If the error discussed here is genuine, assert is not the right way to
handle it.  Asserts can be disabled with the -O option; if someone is
running your script "optimized," execution will continue past the assert
statements where it should have stopped.

Assertions are for making sure things are working the way you think they
are, so you can get a quick failure that you can debug before things
spiral out of control; when not in debug mode, assert statements are
ignored.

They're _not_ for testing fatal errors; those should be handling by
explicitly raising errors other than AssertionError.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ Patriotism is the last refuge of a scoundrel.
\__/ Samuel Johnson
    Kepler's laws / http://www.alcyone.com/max/physics/kepler/
 A proof of Kepler's laws.




More information about the Python-list mailing list