Exception handling vs. hasNext()
Brendan Eich
brendan at mozilla.org
Sat Nov 17 05:50:56 PST 2007
On Nov 16, 2007, at 5:30 PM, Garrett Smith wrote:
> Which is better?
>
> var nodes : int;
> var widgetMap = Widget.instances; // a map.
> var it:Iterator<string> = widgetMap.getKeys();
>
> -- this: --
>
> try {
> widgetMap.get(it.next()).hide();
> }
> catch(Exception e) {
> if(e instanceof StopIteration) {
>
> }
> }
>
>
> -- or this: --
>
> while(it.hasNext()) {
> widgetMap.get(it.next()).hide();;
> }
Neither. This is best:
for each (w in widgetMap)
w.hide();
But your two examples are not equivalent. The first calls the
iterator exactly once, the second loops over all keys. I'm asuming
widgetMap.get(key) returns the corresponding widget value, so for-
each-in is the way to loop, not for-in (and never while).
As in Python, you rarely have to get or make an iterator explicitly;
you almost never have to catch StopIteration.
/be
More information about the Es4-discuss
mailing list