Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make script continues to run after 'raise' statement in ruby?

Tags:

ruby

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
like image 642
SysTest RJR Avatar asked Feb 11 '26 01:02

SysTest RJR


1 Answers

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

  • I recommend looking over the Exceptions section of this ruby style guide - it will give you some quick pointers in the right directions.
  • Also, this answer about never rescuing Exception
like image 187
exbinary Avatar answered Feb 12 '26 16:02

exbinary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!