我有一个对地址进行地理编码的函数。我不希望这个函数消失,所以我试图捕获错误并返回一个元组。 不过,我也想区分错误,为此我在多个地方使用了 try/except 。
是否存在过多的 try/except 之类的情况?您将如何优化这个功能?
这是我的代码:
def geocode(address):
js = ''
try:
urlq = urllib.urlencode({'address':address, 'sensor':'false'})
except Exception, e:
return (False, "Error url-encoding address. Error:%s" % e, js, 'failed')
try:
f = urllib2.urlopen(GEO_URL + urlq)
d = f.read()
except Exception, e:
return (False, "Error making connection. Error:%s" % e, js, 'failed')
#
try:
js = json.loads(d)
except Exception, e:
return (False, "Error converting JSON. Error:%s" % e, js, 'failed')
return (True, '', js, 'ok')
最佳答案
捕获异常
始终是一个坏主意。您想要指定要捕获哪个错误。
try:
...
except URLError, e:
return (False, "Error making connection. Error:%s" % e, js, 'failed')
except ValueError, e:
return (False, "Error converting JSON. Error:%s" % e, js, 'failed')
except UnicodeEncodeError, e:
return (False, "Error unicode formatting. Error:%s" % e, js, 'failed')
同时返回一个元组来指示错误通常不是首选。考虑将 try except 放在调用函数中并让错误向上传播。
关于python - python 函数中有多少个 try/except 就太多了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34913494/