if or exception

Duncan Booth me at privacy.net
Thu Jul 29 04:44:26 EDT 2004


Thomas Lindgaard <thomas at it-snedkeren.BLACK_HOLE.dk> wrote in 
news:pan.2004.07.29.08.13.15.345135 at it-snedkeren.BLACK_HOLE.dk:

> Hi
> 
> Just wondering what is "the right thing to do":
> 
> number = 0
> if len(list) > 0: number = anotherNumber / len(list)
> 
> or 
> 
> try:
>   number = anotherNumber / len(list)
> except:
>   number = 0
> 

Your first suggestion may be the right answer in some situations.

Your second suggestion is never the right answer. This on the other, could 
be a suitable answer:

try:
	number = anotherNumber / len(aList)
except ZeroDivisionError:
	number = 0

Don't use a bare except, it will just mask other errors: if you feel that 
catching an exception is the way to go, then catch only the exceptions that 
you expect. Also, but minor, don't use 'list' as a variable name.

However, it seems to me that I would be unlikely to use either of these. I 
can't think of a situation where I would want a value that is either the 
result of a division, or 0 if the division failed. It is much more likely 
that you want to execute some different code if the list is empty than that 
you want a different value.

If you explained what problem you are solving leads to this code then you 
might get a more useful suggestion about style.




More information about the Python-list mailing list