Python: Handling Errors

上一篇 / 下一篇  2014-04-02 16:34:53 / 个人分类:Python

Handling Errors

You have seen examples of how Python reports errors inChapter 2andChapter 3. Those errors usually contain a lot of information pertaining to what failed and how:

>>> fridge_contents = {"egg":8, "mushroom":20, "pepper":3, "cheese":2,
   "tomato":4, "milk":13}
   >>> if fridge_contents["orange juice"] > 3:
   ...     print("Sure, let's have some juice!")
   ...
   Traceback (most recent call last):
     File "<pyshell#3>", line 1, in <module>
       if fridge_contents["orange juice"] > 3:
   KeyError: 'orange juice'

Oops. There is no orange juice in the fridge right now, but it would be nice to be able to learn this without having to crash out of the program.

You have already learned one way to find out about the keys that are present in a dictionary, by using thekeysmethod of the dictionary and then searching through the list of keys to determine whether the key you want is present. However, there's no reason not to take a shortcut. The last line of the error shown in the preceding code is:

KeyError: 'orange juice'

This says that the error Python encountered was an error with the key in thefridge_contentsdictionary. You can use the error that Python has told you about to brace the program against that particular class of error. You do this with the special wordtry:telling Python to prepare for an error.

Trying Things Out

Atry:statement sets up a situation in which anexcept:statement can follow it. Eachexcept:statement handles the error, which is formally named anexceptionthat was justraisedwhen Python evaluated the code within thetry:statement instead of failing. To start with, useexcept:to handle one type of error — for instance, theKeyErrorthat you get when trying to check the fridge.


Important 

Multiple kinds of exceptions exist, 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, theKeyErrorindicates that the key that was requested from a dictionary isn't present. Similarly, aTypeErrorindicates 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.

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

>>> 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:
   ...     print("Awww, there is no juice. Let's go shopping!")
   ...
   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.


TAG:

 

评分:0

我来说两句

Open Toolbar