LearnPython.org教程(异常处理)

时间:2013-05-22 02:43:09

标签: python except

http://www.learnpython.org/page/Exception%20Handling

我无法修复代码以使用try/except

显示答案

给定代码:

#Handle all the exceptions!
#Setup
actor = {"name": "John Cleese", "rank": "awesome"}

#Function to modify, should return the last name of the actor<br>
def get_last_name():
   return actor["last_name"]

#Test code
get_last_name()
print "All exceptions caught! Good job!"<br>
print "The actor's last name is %s" % get_last_name()

然而,我能够使用以下代码获得正确的显示,但它不使用try/except

#Handle all the exceptions!
#Setup
actor = {"name": "John Cleese", "rank": "awesome"}
x = actor.pop("name")
#Function to modify, should return the last name of the actor<br><br>
def get_last_name():
   name = x.split(" ")
   last_name = name[1] #zero-based index
   return last_name

#Test code
get_last_name()
print "All exceptions caught! Good job!"
print "The actor's last name is %s" % get_last_name()

1 个答案:

答案 0 :(得分:1)

last_name字典中没有actor个密钥,因此当您在最后一行调用get_last_name()时,会抛出KeyError个异常。

def get_last_name():
   try:
      return actor["last_name"]
   except(KeyError):
      ## Handle the exception somehow
      return "Cleese"

显然,不是硬编码"Cleese"字符串,您可以使用上面编写的逻辑来拆分“名称”字段并从中获取姓氏。