2011/02/17

Re-usable Error Handling in Java [cont]

Pure Java version.
Inspired by Exception Handling Templates in Java.



檔案: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();
        }
    }
}
檔案:HandleException.java
編譯:javac HandleException.java
public class HandleException
{
    public static Object ignoreException(IErroneous task, Object... param)
    {
        try {
            return task.process(param);
        } catch (Exception e) {
            System.out.println("Exception found but ignored");
            return null;
        }
    }
}

interface IErroneous
{
    public Object process(Object... param) throws Exception;
}
檔案:UseHello.java
編譯:javac UseHello.java
public class UseHello
{
    public static void main(String[] args)
    {
        // h must be `final`ed in order to be used in following codes,
        // this may be a constraint.
        final Hello h = new Hello();

        IErroneous task = new IErroneous() {
            public Object process(Object... param) throws Exception
            {
                if (!(null == param || 0 == param.length) && param[0] instanceof String) {
                    return h.say((String) param[0]);
                } else {
                    return h.say(null);
                }
            }
        };

        Object ret1 = HandleException.ignoreException(task, (Object) null);
        Print(ret1);

        Object ret2 = HandleException.ignoreException(task, "World");
        Print(ret2);
    }

    private static void Print(Object str)
    {
        if (null == str) {
            System.out.println("Return null");
        } else {
            System.out.println("Return " + str.toString());
        }
    }
}
執行:java UseHello
結果:
Hello Exception found but ignored
Return null
Hello World
Return 1