Conditional catch clause

David Bruant bruant.d at gmail.com
Wed Dec 19 06:32:04 PST 2012


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.

> 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


More information about the es-discuss mailing list