Ruby: 捕获异常后继续循环

基本上,我想这样做(在 Python 或类似的命令式语言中) :

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

在 Ruby 我该怎么做?我知道有 redoretry关键字,但它们似乎重新执行“ try”代码块,而不是继续循环:

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

在 Ruby 中,continue的拼写是 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

打印例外情况:

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