0

在以下脚本中,我的 try 块上发生了 TypeError,它不允许 API 中的 ValueError 发生。我怎样才能跳过该行的执行,self.address, (self.lat, self.lng) = g.geocode(place)以便只捕获来自 Google API 的错误,而不是因为它而在我的代码中发生的错误?

from geopy import geocoders

class GeoCode():
    def __init__(self, place):
        try:
            g = geocoders.GoogleV3()
            self.address, (self.lat, self.lng) = g.geocode(place)
        except ValueError as e:
            print "Failed for address %s with message:\n %s" % (place,e) 
            continue

在测试错误值时

>>> b = GeoCode('nosuchplacecanexist')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "geocode.py", line 7, in __init__
    self.address, (self.lat, self.lng) = g.geocode(place)
TypeError: 'NoneType' object is not iterable

将其更改为:

from geopy import geocoders

class GeoCode():
    def __init__(self, place = "Yashwant Place, Chanakyapuri, New Delhi"):
        try:
            g = geocoders.GoogleV3()
            addr = g.geocode(place)
            if addr is not None:
                self.address, (self.lat, self.lng) = addr 

        except ValueError as e:
            print "Failed for address %s with message:\n %s" % (place,e) 
4

0 回答 0