2

如何在 Ruby 中将恢复写入循环?这是一个示例代码。

#!/usr/bin/ruby
#

a = [1,2,3,4,5]

begin
    a.each{|i|
        puts i
    if( i==4 ) then raise StandardError end # Dummy exception case
    }
rescue =>e
  # Do error handling here
  next # Resume into the next item in 'begin' clause
end

但是,运行时,Ruby 会返回错误消息

test1.rb:13: Invalid next
test1.rb: compile error (SyntaxError)

我正在使用 Ruby 1.9.3。

4

2 回答 2

4

您应该使用retry而不是next; 但这会导致无限循环(retry从头开始重启begin

a = [1,2,3,4,5]
begin
    a.each{|i|
        puts i
        if  i == 4 then raise StandardError end
    }
rescue =>e
    retry # <----
end

如果您想跳过一个项目并继续下一个项目,请在循环内捕获异常。

a = [1,2,3,4,5]
a.each{|i|
    begin
        puts i
        if  i == 4 then raise StandardError end
    rescue => e
    end
}
于 2014-02-04T02:23:56.960 回答
2

将您的异常捕获移动到each块中,例如:

a = [1,2,3,4,5]
a.each do |i|
  puts i
  begin
  # Dummy exception case
  if( i==4 ) then raise StandardError end

  rescue =>e
    # Do error handling here
  end
end
于 2014-02-04T02:24:15.863 回答