开发者

Ruby: Continue a loop after catching an exception

开发者 https://www.devze.com 2022-12-26 07:47 出处:网络
Basically, I want to do something like this (in Python, or similar imperative languages): for i in xrange(1, 5):

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
   开发者_JAVA百科 begin
        do_something_that_might_raise_exceptions(i)
    rescue
        retry    # do_something_* again, with same i
    end
end


In Ruby, continue is spelt next.


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


to print the exception:

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

精彩评论

暂无评论...
验证码 换一张
取 消