如何从Ruby中的rescue子句恢复?

时间:2014-02-04 02:19:39

标签: ruby exception rescue

如何在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。

2 个答案:

答案 0 :(得分: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
}

答案 1 :(得分: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