Download TEAM LinG - LinuxTone.Org

Transcript
Chapter 4
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.
Try It Out
Creating an Exception with Its Explanation
>>> fridge_contents = {“egg”:8, “mushroom”:20, “pepper”:3, “cheese”:2, “tomato”:4,
“milk”:13}
>>> try:
...
if fridge_contents[“orange juice”] > 3:
...
print “Sure, let’s have some juice”
... except KeyError, error:
...
print “Woah! There is no %s” % error
...
Woah! There is no ‘orange juice’
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:
...
print “Sure, let’s have some juice”
... 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:
56
TEAM LinG