0
0
Rubyprogramming~5 mins

Retry for reattempting in Ruby

Choose your learning style9 modes available
Introduction
Sometimes, a task might fail temporarily. Retry helps try the task again until it works or a limit is reached.
When reading a file that might be temporarily locked.
When connecting to the internet and the connection fails.
When asking a user for input until they give a valid answer.
When calling an external service that might be busy.
Syntax
Ruby
begin
  # code that might fail
rescue
  retry
end
The code inside begin runs first.
If an error happens, rescue catches it and retry runs the code again.
Examples
This tries to run code that always fails, then prints a message and tries again forever.
Ruby
begin
  puts "Trying..."
  raise "Error!"
rescue
  puts "Failed, retrying..."
  retry
end
This retries until the count reaches 3, then succeeds.
Ruby
count = 0
begin
  count += 1
  puts "Attempt #{count}"
  raise "Fail" if count < 3
  puts "Success on attempt #{count}!"
rescue
  retry
end
Sample Program
This program tries a task that fails twice, then succeeds on the third try. It shows how retry repeats the code after an error.
Ruby
count = 0
begin
  count += 1
  puts "Try number #{count}"
  raise "Oops" if count < 3
  puts "Done on try #{count}!"
rescue
  puts "Error caught, retrying..."
  retry
end
OutputSuccess
Important Notes
Be careful: retry without a limit can cause infinite loops.
Use a counter to stop retrying after some tries.
retry only works inside rescue blocks.
Summary
retry lets you try code again after an error happens.
Use retry inside rescue to handle temporary problems.
Always limit retries to avoid endless loops.