views:

55

answers:

1

I came across a design that overrides [Scriptable.put][1] in a subclass of ScriptableObject to do some conversion. If the conversion fails the code is throwing an exception. Which means that property assignments like following code can cause a runtime exception to be thrown

    aScriptable.dateOfArrival = aVar;

By default rhino wouldn't let the script catch a runtime exception thrown during [Scriptable.put][1]. So catch block in following code will never run:

    try{    
      aScriptable.dateOfArrival = aVar;
    }catch(e){
    //will not run even if above assignment generates an exception. Script will be terminated instead
    }

Overriding ContextFactory.hasFeature() with following code makes the above catch block work:

    protected boolean hasFeature(Context cx, int featureIndex) {
      if(featureIndex == Context.FEATURE_ENHANCED_JAVA_ACCESS){
        return true;
      }
      return super.hasFeature(cx, featureIndex);
    }

My question is that whether the design decision to make property assignment throw exception is correct or property assignments are never supposed to throw exceptions?

[1]: http://www.mozilla.org/rhino/apidocs/org/mozilla/javascript/Scriptable.html#put(java.lang.String, org.mozilla.javascript.Scriptable, java.lang.Object)

+1  A: 

IMO it doesn't make sense to throw an exception by design from the put method that JS code can't catch. I think throwing an exception on setting a property is fine, although not that common. Note that JS code can easily reconfigure a property (in ECMAScript 5) with a custom setter that throws.

On the other hand, I think it would be quite surprising if a property getter throws an exception.

heycam
Thanks. Can you point me to a relevant resource about custom setters in ECMA script 5?
Tahir Akhtar
Also, I think before ecma 5, there was not way to intercept property access so only host objects could throw exception in property access. Objects created with plain JS code would never throw exception on property access?
Tahir Akhtar
The PDF of the ECMAScript 5 spec is at http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf. Using Object.defineProperty() is how you can define a property with a custom setter.You are correct that according to ECMAScript 3rd edition there's no way for native objects to throw on setting properties.
heycam