gpt4 book ai didi

python - python函数中有多少try/except太多了

转载 作者:行者123 更新时间:2023-11-28 22:39:18 25 4
gpt4 key购买 nike

我有一个地址地理编码功能。我不想让这个函数死掉,所以我试图捕获错误并返回一个元组。但是我也想区分错误,为此我在多个地方使用 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')

最佳答案

捕获 Exception 总是一个坏主意。您要指定要捕获的错误。

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com