3

I'm checking to see if there is any error message in a log file. If an error message found in a log file, then I use 'raise' statement to report the founding. However ruby stops running after executed the 'raise' statement, even when I use 'rescue'. I'd like script continue checking next log file for error after the 'raise' statement, but not sure how. Any help would be appreciated!

        logs_all = s.sudo "egrep -i '#{error_message}' #{log_file}"
        logs_all.each do |hostname, logs|
           unless logs.empty?
            puts line, "Unhappy logs on #{hostname}", line, logs
            happy = false
           end

           begin

            raise "Unhappy logs found! in #{log_file}" unless happy

           rescue raise => error
            puts error.message
           end


        end
SysTest RJR
  • 259
  • 4
  • 12

2 Answers2

7

Your rescue statement doesn't look right:

rescue raise => error

should be:

rescue => error

which is equivalent to:

rescue StandardError => error

If you rescue an exception and don't re-raise it, ruby will continue on. You can easily verify this with something like:

3.times do |i|
  begin
    raise "Raised from iteration #{i}"
  rescue => e
    puts e
  end
end

You'll see that three lines of output are printed.

As a general practice though, you should avoid rescuing Exceptions unless you're going to do something at runtime to rectify the problem. Rescuing and not re-throwing exceptions can hide problems in your code.

And more generally, please follow Sergio's advice above and don't use exceptions as control flow.

Further Reading

Community
  • 1
  • 1
exbinary
  • 1,086
  • 6
  • 8
  • rescue StandardError => error works! Thanks all for your help! – SysTest RJR Jan 29 '13 at 19:34
  • @SysTestRJR - I ran across another question on rescuing exceptions that you might find informative. See the second link under Further Reading. Cheers. – exbinary Jan 31 '13 at 14:45
3

You are using exceptions as control flow mechanism. Don't.

What is it that you want to do with unhappy logs? Print them? To a file, maybe? Do that, don't raise exceptions.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367