views:

124

answers:

2

I seem to be having a brain freeze. I want to catch a possible Ruby exception during a loop through several objects in order to count it as a failure for displaying later, but I do not want execution halted; I want it to skip the bad record and continue. How do I do this again? I don't think I can use retry because that would try the same record again, right?

+3  A: 
some_ary.each do |item|
  begin
    do_something_with item
  rescue Exception => e
    Logger.error "OH NO: #{e}"
  end
end

Execution should continue with errors caught and logged.

Josh Lindsey
This was my first instinct, and I've tried this, but the processing still seemed to halt (it redirected almost immediately when it was processing close to 200 records). I'm doing this for a Rails app, I don't think that would affect anything would it?
Wayne M
In that case, Wayne, it sounds like you might benefit from writing a simple isolated script to potentially tease out a reason why this isn't working in your particular application
Justin Searls
@Wayne, at what level are you catching the exception? If outside of the loop, then the exception will indeed stop the loop. If inside the loop, as @JoshL shows here, then the loop should continue.
Wayne Conrad
A: 

Don't "do" anything. If you've caught an exception and handled it (by adding the bad object to a list or whatever), just continue on your way. Pseudo-code:

for each object foo
    try
        do something risky with foo
    catch
        badobjects.add(foo)
Jonathan Feinberg