Last active
October 13, 2022 07:50
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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