Search code examples
rubyexceptionrescue

How to resume from rescue clause in Ruby?


How can I write resuming into loops in Ruby? Here is a sample code.

#!/usr/bin/ruby
#

a = [1,2,3,4,5]

begin
    a.each{|i|
        puts i
    if( i==4 ) then raise StandardError end # Dummy exception case
    }
rescue =>e
  # Do error handling here
  next # Resume into the next item in 'begin' clause
end

However, when running, Ruby returns the error message

test1.rb:13: Invalid next
test1.rb: compile error (SyntaxError)

I'm using Ruby 1.9.3.


Solution

  • You should use retry instead of next; But this will cause infinite loop (retry restart from the beginning of the begin)

    a = [1,2,3,4,5]
    begin
        a.each{|i|
            puts i
            if  i == 4 then raise StandardError end
        }
    rescue =>e
        retry # <----
    end
    

    If you want skip an item, and continue to next item, catch the exception inside the loop.

    a = [1,2,3,4,5]
    a.each{|i|
        begin
            puts i
            if  i == 4 then raise StandardError end
        rescue => e
        end
    }