Exceptional exits from generators

Andy Wingo wingo at igalia.com
Tue Apr 8 05:47:05 PDT 2014


The current ES6 draft seems to specify that if a running generator
throws an exception, that its state moves to "completed".  It seems to
specify this in §, `GeneratorStart'.  (Oddly, the procedure
described in `GeneratorResume' can return to `GeneratorStart'; spec
strangeness).  Anyway, that means that:

  function *foo() { yield 1; yield 2 }
  var iter = foo()
  iter.next() // => { value: 1, done: false }
  iter.throw(42) // uncaught exception: 42

Up to here all good.  And then we have, according to the spec:

  iter.next() // => { value: undefined, done: true }

I find this very strange.  I would have expected an exception of the
kind "generator is already running", as indeed we entered the running
state but never moved out of that state.

I think that nonlocal exits from within generators should not move the
state to "completed", and should leave them as "suspendedStart".  Beyond
a subjective impression of strangeness, which not all may share, this
part of the specification requires that the continuation of all
GeneratorResume() invocations include a try/catch to set the generator
state to "completed" if the activation resumes and then exits

Of course using "iter.throw" is the easy way to cause an exception, but
it could happen within some function called by the generator.  But if we
decide to remove the try/catch from around the GeneratorResume, it might
make sense to also remove the suspendedStart -> completed transition
that is special-cased in Generator.prototype.throw.

In summary: the completed-on-exception state change is of little utility
but causes overhead in generator implementations in the form of the
mandatory try/catch around GeneratorResume and so it should be removed

If it is removed we could also consider removing the
suspendedStart->completed state change on Generator.prototype.throw.  If
that were done we could remove the suspendedStart state entirely; dead
spec elimination ;)




More information about the es-discuss mailing list