Conditional catch clause

David Bruant bruant.d at gmail.com
Wed Dec 19 08:03:55 PST 2012


Le 19/12/2012 16:38, Claude Pache a écrit :
> Le 19 déc. 2012 à 15:32, David Bruant <bruant.d at gmail.com> a écrit :
>
>> Le 19/12/2012 14:13, Claude Pache a écrit :
>>> Hello,
>>>
>>> In SpiderMonkey (and perhaps other JS engines?), there are conditional catch clauses:
>>>
>>> 	catch (exception if condition)
>>>
>>> Could such a feature added to ECMAScript?
>>>
>>> Rationale: Although try/catch mechanism was initially intended for treating errors, it could be used in normal control flow with non-error condition.
>> Why not just use normal control flow when you want to express non-error conditions?
>> throw/try/catch was indeed intented for treating errors and when I read code, I expect an error path when encountering a try/catch.
> As I've said, iterators throw StopIteration, which may be considered as a non-error.
I completely agree. I have said elsewhere [1] that StopIteration could 
be its own statement. What we want is a way to stop the current call 
frame. The language provides 2 such ways, return and throw. Return can't 
be used because it may result in ambiguities. It could be the same thing 
for throw, but normal use of throw make that throwing a specific object 
is an acceptable hack on StopIteration.

> And in the code example I've given below, I can't use "normal" control flow to stop forEach from iterating over the remaining values, but throwing works fine.
The problem lies in the "bad" forEach design. Arguably every/some may be 
more what you want if stopping after some element is a normal thing in 
your program.
It's barely more hacky.
Arguably, you could create a different array and apply forEach on this 
secondary with .filter.forEach. This may have some performance issue.

In any case, that's more of a hack than an actual throw.

David

[1] https://mail.mozilla.org/pipermail/es-discuss/2012-November/026639.html


More information about the es-discuss mailing list