0

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()
4

1 に答える 1

1

last_nameディクショナリにはキーがないため、最後の行で呼び出すと例外actorがスローされます。KeyErrorget_last_name()

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

明らかに、"Cleese"文字列をハードコーディングする代わりに、上で書いたロジックを使用して「名前」フィールドを分割し、そこから姓を導き出すことができます。

于 2013-05-22T02:46:44.877 に答える