I'm working my way through the book "beginning python" and I came across an
exercise that suggests using Exception trapping to see if a value is in a
dictionary:
fridge={"apple":"A shiny red apple","pear":"a nice ripe
pear","grapes":"seadless grapes"}
food_sought="apple"
fridge_list=fridge.keys();
try:
print "The fridge contains %s" %fridge[food_sought]
except (KeyError):
print "The fridge does not contain %s"%food_sought
I'm fairly certain the book is in error in calling this a "short-cut" since the
has_key method is much less verbose to use, but it brings up a question about
exceptions in general:
In Java using exceptions in the way shown above is a classic anti-pattern since
Exceptions should only be used for..well exceptional conditions.
Is the same true of Python? Or is ok to use Exception handling like the book
suggests?
Thanks in advance,
David Hamilton
_______________________________________________
Tutor maillist - [email protected]
http://mail.python.org/mailman/listinfo/tutor