LearnFrenzy
Sign in Take a free test

Exception Handling · Exception Handling Coding Problems · Question 6

Retry a failing operation a limited number of times in Python Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

Write retry(func, attempts) that calls func until it succeeds, catching ConnectionError, and re-raises the last error after the final attempt. Test it with a simulated flaky connection.

Solution
main.py Run
def retry(func, attempts=3):
    for n in range(1, attempts + 1):
        try:
            return func()
        except ConnectionError as e:
            print(f"attempt {n} failed: {e}")
            if n == attempts:
                raise

def flaky(fail_times):
    calls = {"n": 0}
    def connect():
        calls["n"] += 1
        if calls["n"] <= fail_times:
            raise ConnectionError("server busy")
        return "connected"
    return connect

print(retry(flaky(2)))
try:
    retry(flaky(5))
except ConnectionError:
    print("giving up")

Output Verified by running it on Python 3

attempt 1 failed: server busy
attempt 2 failed: server busy
connected
attempt 1 failed: server busy
attempt 2 failed: server busy
attempt 3 failed: server busy
giving up

Returning inside try ends the loop on success; the bare raise on the last attempt passes the error to the caller.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links