Continue executing a loop after raising an exception

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

if item['id'] throws a KeyError exception the execution terminates.

How to make the for loop continue its execution after the exception?


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