77

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
Santa
  • 11,381
  • 8
  • 51
  • 64

3 Answers3

142

In Ruby, continue is spelt next.

C. K. Young
  • 219,335
  • 46
  • 382
  • 435
  • 10
    @Thayne [British spelling](https://en.wiktionary.org/wiki/spelt#Etymology_1) isn't misspelling! The world does not revolve around the US. :-) (Don't feel bad. I revert Americanisation edits all the time.) – C. K. Young Nov 15 '16 at 18:08
  • 5
    I appologize, I didn't reallize spelt was a valid spelling in british english. – Thayne Nov 16 '16 at 19:28
65
for i in 1..5
    begin
        do_something_that_might_raise_exceptions(i)
    rescue
        next    # do_something_* again, with the next i
    end
end
Carlo
  • 651
  • 5
  • 2
9

to print the exception:

rescue
        puts $!, $@
        next    # do_something_* again, with the next i
end
Konstantin
  • 2,983
  • 3
  • 33
  • 55