简体   繁体   中英

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.

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? Because as things are now, if the exception ever occurs it breaks everything.

EDIT1: I have tried putting continue like so:

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:

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. 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.

Possibly you can use dict 's get method like this in your try block:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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