Ruby:捕获异常后继续循环

San*_*nta 63 ruby loops exception-handling

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

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

我如何在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
Run Code Online (Sandbox Code Playgroud)

Chr*_*ung 118

在Ruby中,continue拼写next.

  • @Thayne [英国拼写](https://en.wiktionary.org/wiki/spelt#Etymology_1)拼写正确!世界并非围绕美国旋转。:-)(不要难过。我一直都在恢复美化内容。) (3认同)
  • 我很抱歉,我没有意识到拼写是英国英语的有效拼写。 (3认同)

小智 51

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

  • 你处于一个循环中,救援结束后,无论救援中是否有“next”,它都会继续循环。 (5认同)

Kon*_*tin 7

打印例外:

rescue
        puts $!, $@
        next    # do_something_* again, with the next i
end
Run Code Online (Sandbox Code Playgroud)