我可以在下面的代码中添加哪些异常处理?我尝试使用不同的输入输出,但它不会给出任何错误,所以我对我可以添加到此程序的异常处理有点困惑。
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 )
答案 0 :(得分:3)
您应首先使用urlopen
块since 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。