Immediate closing of iterators

Jeff Thompson jeff at thefirst.org
Thu Dec 14 21:01:48 PST 2006


This is a follow-up to a bugzilla discussion at:
https://bugzilla.mozilla.org/show_bug.cgi?id=349326

var was_closed = false;
function gen() {
         try {
                 yield 1;
         } finally {
                 was_closed = true;
         }
}

for (var i in gen())
         break;
print("was_closed=" + was_closed);

Right now, this prints "was_closed=false" because when it breaks out of the for loop,
Javascript does not close the iterator, and does not execute the finally clause to
set was_closed true.  I want to argue that Javascript should close the iterator:
* No guarantee is made that the 'finally' clause will ever be
   executed, so if you need it to close a file, etc. it might never happen.
* This seems the opposite of how 'finally' works, which usually means that you can
   be *sure* it will execute, even if the 'try' block throws an exception, etc.
* Python 2.5 and C# both close the iterator and execute the 'finally' clause (as one would expect)
* In fact, before version 2.5, Python gives a compiler error for this code:
   >>> 'yield' not allowed in a 'try' block with a 'finally' clause
   I guess this is because before 2.5, Python did not always close the iterator when
   leaving a for loop from an exception, etc., so they didn't let you write code that
   wouldn't work like you expect.

So, could the spec require Javascript to always close the iterator when leaving a loop?

Thanks,
- Jeff




More information about the Es4-discuss mailing list