底下是範例。
檔案:Test.groovy
編譯:groovyc Test.groovy
class HandleException
{
def static ignore_exception(obj, method, param)
{
try {
return obj."${method}"(param)
} catch (Exception e) {
println "Exception found but ignored"
return null
}
}
}
檔案:Hello.java
編譯:javac Hello.java
public class Hello
{
public int say(String what) throws Exception
{
System.out.print("Hello ");
if (!(null == what)) {
System.out.println(what);
return 1;
} else {
throw new Exception();
}
}
}
檔案:UseHello.java
編譯:javac -cp .:$GROOVY_HOME/embeddable/groovy-all-1.7.7.jar UseHello.java
public class UseHello
{
public static void main(String[] args)
{
Hello h = new Hello();
Object ret1 = HandleException.ignore_exception(h, "say", null);
if (null == ret1) {
System.out.println("Return null");
} else {
System.out.println("Return " + ret1.toString());
}
Object ret2 = HandleException.ignore_exception(h, "say", "World");
if (null == ret2) {
System.out.println("Return null");
} else {
System.out.println("Return " + ret2.toString());
}
}
}
執行:java -cp .:$GROOVY_HOME/embeddable/groovy-all-1.7.7.jar UseHello