Dave
Dave

Reputation: 19120

Simple way to re-run try block if a specific exception occurs?

I'm using Python 3.7 and Django and trying to figure out how to rerun a try block if a specific exception is thrown. I have

for article in all_articles:
    try:
        self.save_article_stats(article)
    except urllib2.HTTPError as err:
        if err.code == 503:
            print("Got 503 error when looking for stats on " + url)
        else:
            raise

What I would like is if a 503 errors occurs, for the section in the "try" to be re-run, a maximum of three times. Is there a simple way to do this in Python?

Upvotes: 1

Views: 261

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476584

You can turn this in a for loop, and break in case the try block was successful:

for article in all_articles:
    for __ in range(3):
        try:
            self.save_article_stats(article)
            break
        except urllib2.HTTPError as err:
            if err.code == 503:
                print("Got 503 error when looking for stats on " + url)
            else:
                raise

In case the error code is not 503, then the error will reraise, and the control flow will exit the for loops.

Upvotes: 3

Related Questions