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

时间:2018-07-23 07:03:55

标签: python try-catch

我有一个函数可以查找输入地址的纬度和经度。但是由于有时地址不返回任何内容(即在Google地图中找不到),因此我想从地址中逐个删除单词,直到它最终可以返回内容为止。该代码可以在所有地址上正常运行,除了少数几个,我在下面显示了其中一个地址:

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')产生错误

但是gmaps_geoencoder('ILAWOD 2 DARAGA ALBAY PHILIPPINES')正确返回了位置坐标。

附言::如果有关系,这是我的函数定义:

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)

1 个答案:

答案 0 :(得分:1)

您的代码在子代码之外引发另一个Exception

我会采用这种方法

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

请注意,在某个时刻try成功了,而您想break。此外,place可能会结束(可能是一个空列表),此时您可以在break子代码下的except处或将其作为停止项while

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

以下是处理更多的代码:

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

我故意没有为您编写此代码,因为我不知道您到底想对lat, lon做什么。您想获得第一个结果吗?或结果清单?我将它留给您处理“ 未知”异常的基本结构。