Python Practice › Exception Handling Programs › Program 14
Retry on failure
Write a Python program that retries an unreliable operation up to 3 times.
Output
attempt 1 failed: slow attempt 2 failed: slow attempt 3 -> OK
Approach
- Loop over attempts; stop on success with
break;elsereports total failure.
Solution
results = iter([TimeoutError("slow"), TimeoutError("slow"), "OK"]) def call_service(): r = next(results) if isinstance(r, Exception): raise r return r for attempt in range(1, 4): try: print("attempt", attempt, "->", call_service()) break except TimeoutError as e: print("attempt", attempt, "failed:", e)else: print("all attempts failed")Output
attempt 1 failed: slow attempt 2 failed: slow attempt 3 -> OK
Line by line
Lines 1-7
A fake service that fails twice and then succeeds.
Lines 9-17
The loop’s else would run only if no attempt succeeded.
Learn the concept
New to this topic? Read the lesson, then come back.