Вопрос

The following code works:

collection.each do |i|
  begin
    next if i > 10
    i += 1
  rescue
    puts "could not process #{ i }"
  end
end

However, when we refactor:

collection.each do |i|
  begin
    increment i
  rescue
    puts "could not process #{ i }"
  end
end

def increment i
  next if i > 10
  i += 1
end

I get invalid next error. Is this a limitation of Ruby (1.9.3)?

Does the begin rescue block work the same way if there is an exception in the increment method?

Это было полезно?

Решение

Your next statement must occur inside a loop. There's no loop inside your increment method.

Exceptions will 'bubble up', so if there's an exception in your increment method, it will be caught by the rescue section of the calling method.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top