python中的异常处理?

时间:2014-06-09 07:58:15

标签: python python-2.7

我可以在下面的代码中添加哪些异常处理?我尝试使用不同的输入输出,但它不会给出任何错误,所以我对我可以添加到此程序的异常处理有点困惑。

import urllib2
import urllib
import json

url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
query = raw_input("What do you want to search for ? >> ")
query = urllib.urlencode( {'q' : query } )
response = urllib2.urlopen (url + query ).read()
data = json.loads ( response )
results = data [ 'responseData' ] [ 'results' ]

for result in results:
    title = result['title']
    url = result['url']
    print ( title + '; ' + url )

1 个答案:

答案 0 :(得分:3)

您应首先使用urlopensince this function can raise IOError围绕try来电。相同for the JSON response,但ValueError。为简单起见,您可以将这两行放在同一个try块中并捕获每个异常:

url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
query = raw_input("What do you want to search for ? >> ")
query = urllib.urlencode({'q' : query })
try:
    response = urllib2.urlopen (url + query).read()
    data = json.loads(response)
except IOError:
    print("Unable to fetch results")
except ValueError:
    print("Invalid response return by the API")
else:
    results = data['responseData']['results']

    for result in results:
        title = result['title']
        url = result['url']
        print("%s; %s" % (title, url))

之后,如果API不一致,访问data['responseData']['results']result[...]也会导致KeyError。您需要评估是否要将异常处理放在任何地方。

旁注:请注意最后print行的字符串格式,比字符串连接更多Pythonic。