2013-05-22 82 views
0

http://www.learnpython.org/page/Exception%20HandlingLearnPython.org教程(異常處理)

我無法修改代碼來顯示使用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

actor字典中沒有last_name密鑰,因此當您在最後一行呼叫get_last_name()時,您將拋出KeyError異常。

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

顯然而不是硬編碼的字符串"Cleese"你可以使用你上面寫的分裂「名稱」字段中的邏輯,並從中獲得姓氏。

+0

謝謝你,我完全在學習python,並從未在以前的編程中使用try/except語句。 – user2407760