Christian Fazzini
Christian Fazzini

Reputation: 19723

How do I make the loop finish when an error is thrown inside?

If I have a loop, and somewhere in the loop, I get an exception or error. How do I keep the loop going?

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

Should I have a rescue block in the loop? Will that make the loop finish? Or is there a better alternative?

Upvotes: 1

Views: 1123

Answers (1)

Benoît
Benoît

Reputation: 15010

You can use add a begin/rescue block. I am not sure there is other ways to do keep loop going if an error is raised.

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

Since your title in the other hand ask for a way to ends the loop.
If you want the loop to ends in the rescue, you can use 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

Upvotes: 3

Related Questions