如何跳过for循环中的错误行

时间:2019-07-17 18:36:25

标签: python for-loop exception

我正在进行的API调用有时在响应中没有某些字段。如果我遇到这些响应之一,那么我的脚本将按预期方式引发KeyError,但随后会完全脱离for循环。有什么办法让它简单地跳过错误的输出并继续循环?

我考虑过尝试将要搜索的所有字段放入列表中,并使用continue语句对其进行迭代,以在遇到缺失字段时使迭代继续进行,但是1)看起来很麻烦,而2)我在输出中有多个级别的迭代。

try:
    for item in result["results"]:
        print(MAJOR_SEP) # Just a line of characters separating the output
        print("NPI:", item['number'])
        print("First Name:", item['basic']['first_name'])
        print("Middle Name:", item['basic']['middle_name'])
        print("Last Name:", item['basic']['last_name'])
        print("Credential:", item['basic']['credential'])
    print(MINOR_SEP)
    print("ADDRESSES")
    for row in item['addresses']:
        print(MINOR_SEP)
        print(row['address_purpose'])
        print("Address (Line 1):", row['address_1'])
        print("Address (Line 2):", row['address_2'])
        print("City:", row['city'])
        print("State:", row['state'])
        print("ZIP:", row['postal_code'])
        print("")
        print("Phone:", row['telephone_number'])
        print("Fax:", row['fax_number'])

    print(MINOR_SEP)
    print("LICENSES")
    for row in item['taxonomies']:
        print(MINOR_SEP)
        print("State License: {} - {}, {}".format(row['state'],row['license'],row['desc']))

    print(MINOR_SEP)
    print("OTHER IDENTIFIERS")
    for row in item['identifiers']:
            print(MINOR_SEP)
            print("Other Identifier: {} - {}, {}".format(row['state'],row['identifier'],row['desc']))

    print(MAJOR_SEP)
except KeyError as e:
    print("{} is not defined.".format(e))

3 个答案:

答案 0 :(得分:2)

那些try ... except块,尤其是那些针对非常具体的错误的块,例如KeyError应该仅在相关的行周围添加。

如果您希望能够继续处理,请至少将该块放在for循环内,以免出现错误,它将跳至迭代中的下一项。但是,甚至更好的方法是验证何时真正需要这些值,并在不需要时将它们替换为虚拟值。

例如:for row in item['addresses']:

可能是:for row in item.get('addresses', []):

因此,您将接受没有地址的物品

答案 1 :(得分:0)

尝试在for之后使用try / except子句。

例如:

for item in result["results"]:
    try:
        # Code here.
    except KeyError as e:
        print("{} is not defined.".format(e))

有关异常的Python文档:https://docs.python.org/3/tutorial/errors.html

您还可以使用contextlib.suppresshttps://docs.python.org/3/library/contextlib.html#contextlib.suppress

示例:

from contextlib import suppress
for item in result["results"]:
    with suppress(KeyError):
        # Code here

答案 2 :(得分:-1)

将try / except块放入for循环中

    for item in result["results"]:
        try:
            print(MAJOR_SEP) # Just a line of characters separating the output
            print("NPI:", item['number'])
            print("First Name:", item['basic']['first_name'])
            print("Middle Name:", item['basic']['middle_name'])
            print("Last Name:", item['basic']['last_name'])
            print("Credential:", item['basic']['credential'])

            print(MINOR_SEP)
            print("ADDRESSES")
            for row in item['addresses']:
                print(MINOR_SEP)
                print(row['address_purpose'])
                print("Address (Line 1):", row['address_1'])
                print("Address (Line 2):", row['address_2'])
                print("City:", row['city'])
                print("State:", row['state'])
                print("ZIP:", row['postal_code'])
                print("")
                print("Phone:", row['telephone_number'])
                print("Fax:", row['fax_number'])

            print(MINOR_SEP)
            print("LICENSES")
            for row in item['taxonomies']:
                print(MINOR_SEP)
                print("State License: {} - {}, {}".format(row['state'],row['license'],row['desc']))

            print(MINOR_SEP)
            print("OTHER IDENTIFIERS")
            for row in item['identifiers']:
                print(MINOR_SEP)
                print("Other Identifier: {} - {}, {}".format(row['state'],row['identifier'],row['desc']))

            print(MAJOR_SEP)
        except KeyError as e:
            print("{} is not defined.".format(e))