Trying Things

A try: statement sets up a situation in which an except: statement can follow it. Each except: statement handles the error, which is formally named an exception, that was just raised when Python evaluated the code within the try: statement instead of failing. To start with, use except: to handle one type of error — for instance, the KeyError that you get when trying to check the fridge.

You have only one line in which to handle the error, which may seem restrictive, but in Chapter 5 you'll learn how to write your own functions so that you can handle errors with more flexibility:

>>> fridge_contents = {"egg":8, "mushroom":20,

"pepper":3, "cheese":2, "tomato":4,


>>> try:

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

... print "Sure, let's have some juice

... except KeyError:

... print "Aww, there's no juice. Lets go


Aww, there's no juice. Lets go shopping

You may find that you need to print more information about the error itself, and this is the information that you have access to.

There are multiple kinds of exceptions, and each one's name reflects the problem that's occurred and, when possible, the condition under which it can happen. Because dictionaries have keys and values, the KeyError indicates that the key that was requested from a dictionary isn't present. Similarly, a TypeError indicates that while Python was expecting one type of data (such as a string or an integer), another type was provided that can't do what's needed.

In addition, when an exception occurs, the message that you would have otherwise seen when the program stops (when you run interactively) can be accessed.

When you've learned more, you'll be able to define your own types of exceptions for conditions that require it.

Was this article helpful?

0 0

Post a comment