Retry on failure

MediumException Handling Programs · 14 of 20

Write a Python program that retries an unreliable operation up to 3 times.

Advertisement
Output
attempt 1 failed: slow
attempt 2 failed: slow
attempt 3 -> OK

Approach

  1. Loop over attempts; stop on success with break; else reports total failure.

Solution

Python
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.

More exception handling programs

← All 20 Exception Handling Programs

Leave a Comment