![](/img/trans.png)
[英]Python customized Exception class should allow to continue the program execution after it has been raised
[英]Continue the execution of a loop after an exception is raised
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
循環在異常后繼續執行?
您可以嘗試捕獲引發的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
對於EAFP
樣式,您可以應用LBYL
,如果在item
找不到id
,則使用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']
您可以先檢查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']
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.