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.
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.
>>> 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)as error: ... print("Woah! There is no %s" % error) ... Woah! There is no 'orange juice'
How It Works
Because there is no key in thefridge_contentsdictionary for“orange juice”, aKeyErroris raised by Python to let you know that no such key is available. In addition, you specified the nameerror,which Python will use to reference a string that contains any information about the error that Python can offer. We achieve this by using the as keyword to assign the value of the KeyError to error. In this case, the string relates to the key that was requested but not present in thefridge_contentsdictionary (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 thoseexceptiontypes 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)as 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 wordpass:
>>> 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) as error: ... print("Woah! There is no %s" % error) ... except (TypeError): ... pass ... Woah! There is no 'orange juice'
There is also anelse:clause that can be put at the end of thetry:block of code. This will only be run when there are no errors to be caught. Like before,elsemay 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 howelse: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.
TAG: