2012-11-14 17 views
1

如果我有一個循環,並在循環中的某個地方,我會得到一個異常或錯誤。我如何保持循環?如何在內部引發錯誤時完成循環?

Foos.each do |foo| 
    .... 
    # Random error/exception thrown here 
    .... 
end 

我應該在循環中有rescue塊嗎?這會使循環完成嗎?還是有更好的選擇?

回答

3

您可以使用添加begin/rescue塊。如果發生錯誤,我不確定是否有其他方法可以保持循環。

4.times do |i| 
    begin 
    raise if i == 2 
    puts i 
    rescue 
    puts "an error happened but I'm not done yet." 
    end 
end 
# 0 
# 1 
# an error happened but I'm not done yet. 
# 3 
#=> 4 

由於您的標題在另一方面要求一種方式來結束循環。
如果您希望循環結束於rescue,則可以使用break

4.times do |i| 
    begin 
    raise if i == 2 
    puts i 
    rescue 
    puts "an error happened and I'm done." 
    break 
    end 
end 
# 0 
# 1 
# an error happened and I'm done. 
#=> nil