[Tutor] Newbie Question on Exceptions...

dsh0105 at comcast.net dsh0105 at comcast.net
Tue May 8 20:36:32 CEST 2007


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


More information about the Tutor mailing list