How It Works

Because there is no key in fridge_contents dictionary for "orange juice", a KeyError is raised by Python to let you know that no such key is available. In addition, you specified the name error, which Python will use to reference a string that contains any information about the error that Python can offer. In this case, the string relates to the key that was requested but not present in the fridge_contents dictionary (which is, again, "orange juice").

There may be times when you handle more than one type of error in exactly the same way; and in those cases, you can use a tuple with all of those exception types described:

>>> fridge_contents = {"egg":8, "mushroom":20, "pepper":3, "cheese":2, "tomato":4, "milk":13}

>>> try: ... if fridge_contents["orange juice"] > 3:

... except (KeyError, TypeError), error: ... print "Woah! There is no %s" % error

Woah! There is no 'orange juice'

If you have an exception that you need to handle, but you want to handle it by not doing anything (for cases in which failure isn't actually a big deal), Python will let you skip that case by using the special word pass:

>>> fridge_contents = {"egg":8, "mushroom":20, "pepper":3, "cheese":2, "tomato":4,


... if fridge_contents["orange juice"] > 3:

... except KeyError, error:

Woah! There is no 'orange juice'

There is also an else: clause that can be put at the end of the try: block of code. This will only be run when there are no errors to be caught. Like before, else may not be the obvious choice for a name that could better be described as "in case it all works" or "all_clear" or something like that. By now, however, you can see how else: has become a flexible catch-all that means "in case something happens" although it's not consistent. In any case, it's there for you to use.

Was this article helpful?

0 0

Post a comment