Rhino 中的 JS 属性赋值抛出异常有意义吗?

发布于 2024-09-10 08:30:46 字数 1248 浏览 2 评论 0 原文

我遇到了一个在 ScriptableObject 进行一些转换。如果转换失败,代码将引发异常。这意味着像下面的代码这样的属性分配可能会导致抛出运行时异常。

    aScriptable.dateOfArrival = aVar;

默认情况下,rhino 不会让脚本捕获在 [Scriptable.put][1] 期间抛出的运行时异常。因此,以下代码中的 catch 块永远不会运行:

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

使用以下代码重写 ContextFactory.hasFeature() 使上述 catch 块起作用:

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

我的问题是,使属性分配抛出异常的设计决策是否正确或属性分配永远不应该抛出异常?

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

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

櫻之舞 2024-09-17 08:30:46

在我看来,从 JS 代码无法捕获的 put 方法中设计抛出异常是没有意义的。我认为在设置属性时抛出异常是可以的,尽管并不常见。请注意,JS 代码可以使用抛出异常的自定义 setter 轻松重新配置属性(在 ECMAScript 5 中)。

另一方面,我认为如果属性获取器抛出异常,那将是非常令人惊讶的。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文