Skip to content

Instantly share code, notes, and snippets.

@sephraim
Last active October 13, 2022 07:50
Show Gist options
  • Save sephraim/314ed86c79aab8cbd10bc34f56d07294 to your computer and use it in GitHub Desktop.
Save sephraim/314ed86c79aab8cbd10bc34f56d07294 to your computer and use it in GitHub Desktop.
[Try blocks in Ruby] How to use a begin...rescue...else...ensure block for exception handling
# Max number of retries if error occurs while pruning index
MAX_NUM_RETRIES = 3
# Number of seconds to wait between retries
RETRY_TIMEOUT_SECONDS = 5
begin
retries ||= 0
# Do something
rescue StandardError => e
# Rescue exception type #1
if (retries += 1) < MAX_NUM_RETRIES
sleep RETRY_TIMEOUT_SECONDS
retry
else
puts "ERROR: #{e}"
end
rescue SomeOtherError => e
# Rescue exception type #2
puts "ERROR: #{e}"
else
# Do something else if no exception
ensure
# Do something regardless of exception / no exception
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment