简体   繁体   English

异常后继续嵌套循环

[英]Continue a nested loop after exception

I have a nested loop to get certain JSON elements the way I want, but occasionally, the API I'm fetching from gets messy and it breaks some of the fields - I am not exactly sure how to handle this since It seems to be different each time, so I'm wondering if there is a way to continue a nested for loop even if an exception occurs inside it, or at least go back to the first loop and continue again.我有一个嵌套循环,可以按照我想要的方式获取某些 JSON 元素,但有时,我从中获取的 API 会变得混乱并且会破坏某些字段 - 我不确定如何处理这个问题,因为它似乎有所不同每次,所以我想知道是否有办法继续嵌套的 for 循环,即使其中发生异常,或者至少返回到第一个循环并再次继续。

My code is like this:我的代码是这样的:

 fields = ['email', 'displayname', 'login']
    sub_fields = ['level', 'name']

    all_data = []
    for d in data:
        login_value = d['login']
        if login_value.startswith('3b3'):
            continue
        student = fetched_student.student_data(login_value)
        student = json.loads(student)
        final_json = dict()
        try:
            for field in fields:
                #print ("Student field here: %s" % student[field])
                final_json[field] = student[field]
        except Exception as e:
            print (e) # this is where I get a random KeyValue Error
            #print ("Something happening here: %s " % final_json[field])
        finally:
            for sub_field in sub_fields:
                for element in student['users']:
                    if element.get(sub_field):
                        final_json[sub_field] = element.get(sub_field)
                for element in student['campus']:
                    if element.get(sub_field):
                        final_json[sub_field] = element.get(sub_field)
        all_data.append(final_json)
        print (all_data)

Is there a way to just go back to the first try block and continue after the exception has occurred or simply just ignore it and continue?有没有办法在异常发生后回到第一个 try 块并继续,或者只是忽略它并继续? Because as things are now, if the exception ever occurs it breaks everything.因为就像现在的情况,如果异常发生,它会破坏一切。

EDIT1: I have tried putting continue like so: EDIT1:我试过像这样继续:

try:
    for field in fields:
        #print ("Student field here: %s" % student[field])
        final_json[field] = student[field]
except Exception as e:
    print (e)
    continue
    for sub_field in sub_fields:
        for element in student['users']:

But it still fails regardless.但无论如何它仍然失败。

Use this for the try block:将此用于 try 块:

for field in fields:
   try:
       #print ("Student field here: %s" % student[field])
       final_json[field] = student[field]
    except Exception as e:
        print (e)
        continue
for sub_field in sub_fields:
    for element in student['users']:

The issue is due to the indentation level of the try block, the continue was affecting the outer most loop.问题是由于 try 块的缩进级别,continue 影响了最外层的循环。 Changing the try block to be inside of the loop will catch the error in that loop and continue the iteration of that specific loop.将 try 块更改为循环内部将捕获该循环中的错误并继续该特定循环的迭代。

Possibly you can use dict 's get method like this in your try block:可能你可以在你的try块中使用dict的 get 方法:

try:
    for field in fields:
        #print ("Student field here: %s" % student[field])
        final_json[field] = student.get(field, "") # 2nd arg is fallback object

Depending on what is needed, you can pass in an fresh dict (aka JSON object), fresh list (aka JSON array), or a str like above to suit your downstream needs.根据需要,您可以传入一个新的dict (又名 JSON 对象)、新的list (又名 JSON 数组)或类似上面的str以满足您的下游需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM