You want to retry a block up to 3 times if an error occurs, then stop retrying. Which code correctly implements this in Ruby?
hard📝 Application Q15 of 15
Ruby - Error Handling
You want to retry a block up to 3 times if an error occurs, then stop retrying. Which code correctly implements this in Ruby?
Aattempts = 0
begin
# risky code
attempts += 1
rescue
retry if attempts < 3
end
Battempts = 0
begin
attempts += 1
# risky code
rescue
retry
end
Cattempts = 0
begin
# risky code
rescue
retry unless attempts > 3
end
Dattempts = 0
begin
# risky code
rescue
attempts += 1
retry if attempts < 3
end
Step-by-Step Solution
Solution:
Step 1: Understand retry with counter
We must increment attempts inside rescue to count retries after errors.
Step 2: Check retry condition
Retry only if attempts < 3 to limit retries to 3 times.
Step 3: Verify code correctness
attempts = 0
begin
# risky code
rescue
attempts += 1
retry if attempts < 3
end increments attempts in rescue and retries if attempts < 3, correctly limiting retries.
Final Answer:
attempts = 0
begin
# risky code
rescue
attempts += 1
retry if attempts < 3
end -> Option D
Quick Check:
Increment attempts in rescue before retry = C [OK]
Quick Trick:Increment attempts in rescue before retry condition [OK]
Common Mistakes:
Incrementing attempts before begin block
Retrying without limiting attempts
Using wrong retry condition logic
Master "Error Handling" in Ruby
9 interactive learning modes - each teaches the same concept differently