1

The following Ruby fiber raises a StopIteration exception the first time it is resumed, but not subsequently. Is it possible to make a fiber which raises the exception every time it is resumed?

f = Fiber.new do
  while true
    raise StopIteration
  end
end
Joe Nelson
  • 549
  • 5
  • 12
  • Does the exception have to bubble up and out of the fiber's execution block? If yes, then by definition the fiber will terminate. If not, just make use of `begin..rescue` inside the loop. – d11wtq Jun 02 '12 at 14:23
  • PS: `while true ... end` is better expressed in ruby as `loop do ... end`. – d11wtq Jun 02 '12 at 14:23
  • Yeah, it does need to bubble out of the Fiber. I was puzzled because this non-fiber function works correctly. def g; while true; raise StopIteration; end; end – Joe Nelson Jun 02 '12 at 14:30
  • Well you can certainly call a method that raises an exception repeatedly, since the method has to return anyway. If you return from the fiber's block (or terminate it with an exception), then the fiber can't be resumed... you'd have to make a new fiber. – d11wtq Jun 02 '12 at 14:37
  • 1
    One strange quirk about loop vs while true. Loop silently rescues StopIteration exceptions. http://rubydoc.info/stdlib/core/1.9.2/StopIteration – Joe Nelson Jun 02 '12 at 15:36

0 Answers0