Skip to content

Instantly share code, notes, and snippets.

@pootsbook
Created November 3, 2012 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pootsbook/4008251 to your computer and use it in GitHub Desktop.
Save pootsbook/4008251 to your computer and use it in GitHub Desktop.
Iterate through an array while rescuing exceptions
# https://github.com/rtomayko/tilt/blob/master/lib/tilt.rb
# Try each of the classes until one succeeds. If all of them fails,
# we'll raise the error of the first class.
first_failure = nil
klasses.each do |klass|
begin
klass.new { '' }
rescue Exception => ex
first_failure ||= ex
next
else
return klass
end
end
raise first_failure if first_failure
@pootsbook
Copy link
Author

This seems like a good example of iterating through a list of options and trying each one, rescuing exceptions as we go. The first_failure gets stored and returned to the user if all fail. In an ideal situation the exceptions should be gathered and appropriate error messages bubbled up to the UI.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment