循环浏览列表时处理错误

2024-06-13 12:21:22 发布

您现在位置:Python中文网/ 问答频道 /正文

在标题所述的列表上进行迭代时,我在处理错误时遇到了问题。我正在IPSRList中存储IP列表,并对它们进行迭代,以检查它们在GeoIP2数据库中是否有任何数据。问题是它在一个不在数据库中的ip上迭代,它会破坏程序,我正在尝试学习如何处理这个错误,以便它继续迭代并返回所需的数据

def getGeoIp(ipSrcList):

    reader = geoip2.database.Reader('./GeoLite2-City.mmdb')
    for ip in ipSrcList:
        try:
            response = reader.city(str(ip))
            end
        
        except ValueError:
            print(f'{ip} not found in the databse')

    
    print(response)
    return response

这是我收到的错误 228,在

    raise geoip2.errors.AddressNotFoundError(
geoip2.errors.AddressNotFoundError: The address <IP ADDRESS HERE> is not in the database.

问题是程序应该继续遍历列表,直到所有的列表都被遍历


Tags: 数据in程序ip数据库列表response错误
1条回答
网友
1楼 · 发布于 2024-06-13 12:21:22

你有

try: 
    # Do some work
except ValueError:
    # Handle the exception of type ValueError or any of its sub-classes.

问题是代码引发了geoip2.errors.AddressNotFoundError类型的错误,它是RuntimeError的子类,而不是ValueError。(ValueError和RuntimeError都是subclasses of Exception。)

如果您还不清楚,那么请阅读Python documentation或您最喜欢的Python书籍中的Python异常处理。以下是Python文档中的要点:

Then if [the error's] type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement.

A class in an except clause is compatible with an exception if it is the same class or a base class thereof (but not the other way around — an except clause listing a derived class is not compatible with a base class).

相关问题 更多 >