为什么在此"try...except"块中未捕获/处理错误?



我有一个函数,可以查找输入地址的纬度和经度。但由于有时地址什么都不返回(即在谷歌地图中找不到(,我想从地址中一个接一个地删除单词,直到它最终可以返回一些东西。该代码对所有地址都运行良好,除了少数地址,我在下面展示了其中一个地址:

place = '033 SEGOVIA ST ILAWOD 2 DARAGA ALBAY PHILIPPINES'
while True:
place = place.split(' ', 1)[1] # remove the first word from the address
try:
lat, lon, res = gmaps_geoencoder(place)
except:
place = place.split(' ', 1)[1]
lat, lon, res = gmaps_geoencoder(place)
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-174-5b96029e3dbf> in <module>()
5     try:
----> 6         lat, lon, res = gmaps_geoencoder(place)
7     except:
<ipython-input-1-3bfa8158ebff> in gmaps_geoencoder(address)
12     res = req.json()
---> 13     result = res['results'][0]
14     lat = result['geometry']['location']['lat']
IndexError: list index out of range
During handling of the above exception, another exception occurred:
IndexError                                Traceback (most recent call last)
<ipython-input-174-5b96029e3dbf> in <module>()
7     except:
8         place = place.split(' ', 1)[1]
----> 9         lat, lon, res = gmaps_geoencoder(place)
<ipython-input-1-3bfa8158ebff> in gmaps_geoencoder(address)
11     req = requests.get(GOOGLE_MAPS_API_URL+'?address='+address+'&key='+API_key)
12     res = req.json()
---> 13     result = res['results'][0]
14     lat = result['geometry']['location']['lat']
15     lon = result['geometry']['location']['lng']
IndexError: list index out of range

为什么它不能捕获此地址的异常?为什么它能适用于大多数其他地址?

当我手动尝试该功能时,它运行良好:

gmaps_geoencoder('033 SEGOVIA ST ILAWOD 2 DARAGA ALBAY PHILIPPINES')产生错误,

gmaps_geoencoder('SEGOVIA ST ILAWOD 2 DARAGA ALBAY PHILIPPINES')产生错误,

gmaps_geoencoder('ST ILAWOD 2 DARAGA ALBAY PHILIPPINES')产生错误,

但是CCD_ 4正确地返回位置坐标。

p。S.:如果重要的话,下面是我的函数定义:

def gmaps_geoencoder(address):
req = requests.get(GOOGLE_MAPS_API_URL+'?address='+address+'&key='+API_key)
res = req.json()
result = res['results'][0]
lat = result['geometry']['location']['lat']
lon = result['geometry']['location']['lng']
return lat, lon, str(res)

您的代码在except子代码中引发另一个Exception

我会采用这种方法

while True:
try:   
lat, lon, res = gmaps_geoencoder(place)
except:
place = place.split(' ', 1)[1]

请注意,在某个时刻try成功,并且您希望break。此外,place可能会结束(可能是一个空列表(,此时您可以在except子代码下使用break,也可以将其作为while中的停止项

最后但并非最不重要的是,强烈建议不要在没有特定Exceptions的情况下使用except:。我建议调查一下你想在那里抓到哪个Exceptions

这是一个经过更多处理的代码:

while len(place) > 1 :
try:   
lat, lon, res = gmaps_geoencoder(place)
break
except:
place = place.split(' ', 1)[1]

我故意不给你写这个代码,因为我不知道你到底想用lat, lon做什么。你想得到第一个结果吗?还是结果列表?我留给您的是处理">未知"异常的基本结构。

最新更新