Julia Error Recovery Patterns
Error recovery is code that tries again after a failure and falls back to a fixed value when the tries run out. The number of tries is fixed before the loop starts.
A retry loop tries again until one try works
The first two tries fail. The third try returns 42.
function load_value(attempt)
if attempt < 3
error("not ready")
end
return 42
end
function load_with_retries()
for attempt in 1:3
try
return load_value(attempt)
catch
nothing
end
end
return 0
end
println(load_with_retries())A fixed fallback answers when every try fails
Every try fails here. The loop then returns 7.
function always_fails(attempt)
error("down")
end
function load_or_fallback()
for attempt in 1:3
try
return always_fails(attempt)
catch
nothing
end
end
return 7
end
println(load_or_fallback())The loop can count how many tries it used
The first try fails and the second works. The count printed is 2.
function flaky(attempt)
if attempt < 2
error("busy")
end
return 10
end
function attempts_used()
used = 0
for attempt in 1:3
used = attempt
try
flaky(attempt)
break
catch
nothing
end
end
return used
end
println(attempts_used())Example
function load_value(attempt)
if attempt < 3
error("not ready")
end
return 42
end
function load_with_retries()
for attempt in 1:3
try
return load_value(attempt)
catch
nothing
end
end
return 7
end
function always_fails(attempt)
error("down")
end
function fallback_only()
for attempt in 1:3
try
return always_fails(attempt)
catch
nothing
end
end
return 7
end
println(load_with_retries())
println(fallback_only())Key points
- Retry loop: a loop that runs the same try again up to a fixed count.
- Attempts: the count of tries is set before the loop starts.
- Fallback: a fixed value the code returns when every try fails.
- Success: a try that works ends the loop at once.
- Catch: a failed try is caught inside the loop so the next try can run.
In this example, load_value fails on the first two tries and returns 42 on the third, so load_with_retries prints 42. always_fails fails on every try, so fallback_only prints the fallback 7.
Note
a caught error prints nothing on its own, so the loop prints only the final value.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
A retry loop tries 3 times. Every try fails, and the fallback is 7. What does the loop return?