[Tutor] Newbie Question on Exceptions...

Alan Gauld alan.gauld at btinternet.com
Tue May 8 22:11:08 CEST 2007


<dsh0105 at comcast.net> wrote

> fridge={"apple":"A shiny red apple","pear":"a nice ripe 
> pear","grapes":"seadless grapes"}
> food_sought="apple"
> fridge_list=fridge.keys();

Not sure what this line is for...

> try:
>    print "The fridge contains %s" %fridge[food_sought]
> except (KeyError):
>    print "The fridge does not contain %s"%food_sought

This is a fairly common Python idiom.

> I'm fairly certain the book is in error in calling this a 
> "short-cut"

I agree, its not much of a shortcut. but oit is a common Python idiom.

> In Java using exceptions in the way shown above is
> a classic anti-pattern since Exceptions should only
> be used for..well exceptional conditions.

There are a few reasons for this in Jave, not least that
Exceptions are quite expensive in Java whereas they
are relatively cheap in Python.

> Or is ok to use Exception handling like the book suggests?

Its generally OK but at the same time don't overdo it.
Exceptions have a lot in common with gotos. They can
obfuscate the flow of code unless the try block is short
and simple. Personally I prefer to use exception for real
exceptions when possible, but sometimes they do offer
a neat way of expressing things. And of course accessing
a non existent key is an exception!

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list