簡體   English   中英

Groovy結束異常與引發的異常不同

[英]Groovy end exception different from exception thrown

在Groovy中,我遇到了一種極其奇怪的行為。 當我從腳本中的閉包引發異常時,所引發的最終異常有所不同。

以下是代碼和詳細信息:

public class TestDelegate {

    def method(Closure closure) {
        closure.setResolveStrategy(Closure.DELEGATE_FIRST);
        closure.delegate = this;
        closure.call();
    }

    public static void main(String[] args) {
        // Make Script from File
        File dslFile = new File("src/Script.dsl");
        GroovyShell shell = new GroovyShell();
        Script dslScript = shell.parse(dslFile);

        TestDelegate myDelegate = new TestDelegate();

        dslScript.metaClass.methodMissing = {
            // will run method(closure)
            String name, arguments ->
            myDelegate.invokeMethod(name, arguments);
        }

        dslScript.metaClass.propertyMissing = {
            String name ->

            println "Will throw error now!"
            throw new MyOwnException("errrrror");
        }

        dslScript.run();
    }
}

class MyOwnException extends Exception {
    public MyOwnException(String message) {
        super(message);
    }
}

Script.dsl:

method {
    println a;
}

因此計划是,當我在TestDelegate運行main()方法時,它將運行DSL腳本,該腳本需要方法method() 在腳本中找不到它,它將調用methodMissing ,然后從myDelegate調用method() ,后者又調用閉包,將委托設置為testDelegate 到現在為止還挺好。 然后,應該使用閉包嘗試打印出未定義的“ a”,因此將引發propertyMissing ,這將引發MyOwnException

但是,當我運行代碼時,將得到以下輸出:

Will throw error now!
Exception in thread "main" groovy.lang.MissingPropertyException: No such property: a for class: TestDelegate

現在,它必須已經到達該catch塊,因為它打印了“現在將拋出錯誤!”。 它一定也拋出了MyOwnException 但沿線某處, MyOwnException轉化為MissingPropertyException ,我不知道為什么。 有人有什么主意嗎?

PS如果我從TestDelegate#method()刪除了closure.setResolveStrategy(Closure.DELEGATE_FIRST) ,則代碼將按預期方式工作並拋出MyOwnException 但是我確實需要為我的DSL項目設置setResolveStrategy(Closure.DELEGATE_FIRST) 而且,我寧願知道此問題的根本原因,而不是僅僅刪除一兩行,而在不了解原因的情況下看到它是否起作用。

我想這就是實際上發生的事情:使用委托,首先解決的策略,Groovy的運行時會首先嘗試訪問屬性amyDelegate ,這會導致MissingPropertyException ,因為沒有這樣的屬性存在。 然后,它嘗試propertyMissing ,這將引發MyOwnException 最終,運行時放棄並拋出遇到的第一個異常(設計決策),恰好是MissingPropertyException

使用所有者優先解決策略,首先會查詢propertyMissing ,因此最終會MyOwnException

查看下面的堆棧跟蹤和源代碼應提供更多證據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM