Conditional catch clause

Claude Pache claude.pache at gmail.com
Wed Dec 19 05:13:08 PST 2012


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. 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
		}


It is arguably not an important feature, but it is a nice one. Note also that the "if condition" construct is the same as in array comprehension (I want to say: it is not "yet another syntax").

Claude


More information about the es-discuss mailing list