如何在捕获异常后继续执行?

时间:2013-06-18 09:01:55

标签: python-2.7 twython

我正在使用twython从twitter上获取一些推文。要获取推文我使用try / except,比如

for follower in followers_file_id:
    follower = follower.strip()
    try:     
      if req_user_settings > max_user_settings_req or req_user_tweets > max_tweets_req:
        time.sleep(15 * 60)
        tweets_file_name = tweetsFileName(followed_user)

      user_settings = twitter.show_user(user_id = follower)
      req_user_settings += 1

      if not user_settings['protected'] and user_settings['statuses_count'] > 0:
        tweets = twitter.get_user_timeline(user_id = follower, count = 200, page = 1)
        req_user_tweets += 1

      n_tweets =tweets[0]['user']['statuses_count']
      n_loops = n_tweets // max_tweets_per_page + 1
      if n_loops > max_tweet_pages:
        n_loops = max_tweet_pages

      if tweets[0]['user']['lang'] == 'en':
        n_crawled_tweets = writeTweets(tweets, tweets_file_name, n_crawled_tweets)

      for i_loop in range(1, n_loops):        
        tweets = twitter.get_user_timeline(user_id = follower, count = 200, page = i_loop+1)
        n_crawled_tweets = writeTweets(tweets, tweets_file_name, n_crawled_tweets)
        req_user_tweets += 1

    except TwythonError as e:
      print str(e)

如何在打印错误后告诉程序继续执行?打印错误后立即启动,程序停止。

2 个答案:

答案 0 :(得分:1)

一旦发生异常,将立即保留整个try块。 如果您想在异常后继续,则需要先捕获异常

Try:
   some code here
except TwythonError as e:
   print e

some more code here

答案 1 :(得分:1)

try:
  some code here
except TwythonError as e:
  print e
finally:
   #continue

请记住,代码将始终通过finally部分,因此,您只需执行抛出异常的代码,在try部分内部,其余部分在finally部分中执行。