Ruby: Continue a loop after catching an exception

RubyException HandlingLoops

Ruby Problem Overview


Basically, I want to do something like this (in Python, or similar imperative languages):

for i in xrange(1, 5):
    try:
        do_something_that_might_raise_exceptions(i)
    except:
        continue    # continue the loop at i = i + 1

How do I do this in Ruby? I know there are the redo and retry keywords, but they seem to re-execute the "try" block, instead of continuing the loop:

for i in 1..5
    begin
        do_something_that_might_raise_exceptions(i)
    rescue
        retry    # do_something_* again, with same i
    end
end

Ruby Solutions


Solution 1 - Ruby

In Ruby, continue is spelt next.

Solution 2 - Ruby

for i in 1..5
    begin
        do_something_that_might_raise_exceptions(i)
    rescue
        next    # do_something_* again, with the next i
    end
end

Solution 3 - Ruby

to print the exception:

rescue
        puts $!, $@
        next    # do_something_* again, with the next i
end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSantaView Question on Stackoverflow
Solution 1 - RubyChris Jester-YoungView Answer on Stackoverflow
Solution 2 - RubyCarloView Answer on Stackoverflow
Solution 3 - RubyKonstantinView Answer on Stackoverflow