引发异常后继续执行循环

时间:2014-07-25 19:20:39

标签: python django

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

如果item['id']抛出KeyError异常,则执行终止。

如何使for循环在异常后继续执行?

4 个答案:

答案 0 :(得分:5)

您可以尝试捕获引发的KeyError异常,然后将其丢弃:

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

答案 1 :(得分:4)

EAFP样式外,如果LBYL中找不到id,您可以应用item并使用continue

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']

答案 2 :(得分:1)

如果item['id']存在,您可以先检查:

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']

如果不存在,请使用None

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

如果不存在,请使用其他默认值:

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']

答案 3 :(得分: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