Introduction
Sometimes, a task might fail temporarily. Retry helps try the task again until it works or a limit is reached.
begin # code that might fail rescue retry end
begin puts "Trying..." raise "Error!" rescue puts "Failed, retrying..." retry end
count = 0 begin count += 1 puts "Attempt #{count}" raise "Fail" if count < 3 puts "Success on attempt #{count}!" rescue retry end
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
retry keyword do in Ruby when used inside a rescue block?retry keyword is used inside a rescue block to repeat the code in the begin block.retry is called, Ruby restarts the begin block from the start, trying again.begin block from the beginning. -> Option Bretry keyword must be inside the rescue block to reattempt the begin block.retry inside rescue, which is the correct syntax.attempts = 0
begin
attempts += 1
puts "Try #{attempts}"
raise 'Error' if attempts < 3
rescue
retry
end
puts 'Done'begin puts 'Start' raise 'Oops' rescue puts 'Error caught' retry puts 'After retry' end
retry statement causes the code to jump back to begin, so any code after retry in rescue is never run.puts 'After retry' is after retry and will never execute, making it unreachable.Pass the test and this pattern moves unknown