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()
答案 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"
字符串,您可以使用上面编写的逻辑来拆分“名称”字段并从中获取姓氏。