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