Conditional catch clause

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


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. 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 (, 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").


More information about the es-discuss mailing list