How best to write this try/except block?

brueckd at tbye.com brueckd at tbye.com
Wed Apr 3 12:43:35 EST 2002


On 3 Apr 2002, Roy Smith wrote:

> I've got a dictionary d, which may or may not have a value I'm looking
> for.  If it does, I want to do a few things.  If it doesn't, I want to
> do a few other things.  I could write:
>
> try:
>     value = d[key]
>     foo = stuff (value)
> except KeyError:
>     foo = otherStuff (key)
>
> which is fine as long as I can guarantee (hint: I can't) that stuff()
> doesn't raise a KeyError.

Sounds like stuff() is poorly-implemented or you're not using it the
right way. Why would stuff() be letting a KeyError get by uncaught? (seems
odd to me) You have to decide one of three ways:

1 - decide that it doesn't make sense for stuff() to not catch the
KeyError, so fix stuff().

2 - decide that it's ok for stuff to raise a KeyError because you have
some other action to take, so your resulting code would look like:
  try:
    value = d[key]
    try:
      foo = stuff(value)
    except KeyError:
      foo = somethingelse(value)
  except KeyError:
    foo = otherstuff(key)

3 - decide that if stuff raises a KeyError, it means this whole operation
you're doing failed, so leave the code as it is (and let either KeyError
be caught by your one except clause).

-Dave






More information about the Python-list mailing list