[Django]-Continue the execution of a loop after an exception is raised

5👍

You can try and catch the KeyError exception that gets raised and then discard it:

for item in r.get_iterator():
    if 'retweeted_status' in item:
        print('aa')
    else:
        try:
            id_twitty = item['id']
            count_ret = item['retweet_count']
        except KeyError:
            pass
👤zbs

4👍

Alternatively to EAFP style, you can apply LBYL and use continue if id not found in item:

for item in r.get_iterator():
    if 'retweeted_status' in item:
        print('aa')
    elif 'id' not in item:
        continue
    else:
        id_twitty = item['id']
        count_ret = item['retweet_count']
👤alecxe

1👍

You could either check first if item['id'] exists:

for item in r.get_iterator():
    if 'retweeted_status' in item:
        print('aa')
    else:
        if 'id' in item:
            id_twitty = item['id']
            count_ret = item['retweet_count']

Or use None if it doesn’t exist:

for item in r.get_iterator():
    if 'retweeted_status' in item:
        print('aa')
    else:
        id_twitty = item.get('id')
        count_ret = item['retweet_count']

Or use some other default value if it doesn’t exist:

default_id = 0

for item in r.get_iterator():
    if 'retweeted_status' in item:
        print('aa')
    else:
        id_twitty = item.get('id', default_id)
        count_ret = item['retweet_count']
👤janos

1👍

for item in r.get_iterator():
    if 'retweeted_status' in item:
        print('aa')
    else:
        id_twitty = item.get('id', None)
        count_ret = item.get('retweet_count', None)
        if not id_twitty or not count_ret:
            print "could not retrieve id or count"
            # handle error here
👤Sid

Leave a comment