Conditional catch clause

Claude Pache claude.pache at gmail.com
Wed Dec 19 07:38:32 PST 2012


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. 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. It is not written in stone that throw/try/catch must be used only for what it was primarily intended for.

> 
>> ES.next sanction this pattern with StopIteration. In this case, it would be nice to have a catch clause listening only what is wanted, without having to add code for filtering out and rethrowing. Here is an example of use:
>> 
>> 	Map.prototype.some = function(f, o) {
>> 		var ok = {} // an arbitrary private object
>> 		try {
>> 			this.forEach(function(v, k, m) {
>> 				if (f.call(o, v, k, m))
>> 					throw ok
>> 			})
>> 		}
>> 		catch (e if e === ok) {
>> 			return true
>> 		}
>> 		return false
>> 	}
>> 
>> instead of, e.g.,
>> 
>> 		catch (e) {
>> 			if (e !== ok)
>> 				throw e
>> 			return true
>> 		}
> I don't see the benefit from your example. You're basically removing one or 2 lines of code in an hardly more expressive way. Your above example could even be rewritten as:
> 
>        catch (e) { if (e !== ok) throw e
>            return true
>        }
> 
> That could be a code convention without needing to be part of the language.
> 
> Do you have example of code in the wild that would benefit (performance, readability, etc.) from such an addition?
> 
> David

I haven't search if there are code in the wild that would benefit, and in any case, the benefit would indeed be small (slightly less code and better readability), but I didn't see counterindications against that syntax either.

Claude


More information about the es-discuss mailing list