try-catch arround回调

时间:2012-10-30 23:27:57

标签: java callback try-catch

public class Test {

    public static void main(String[] args) {

        try {
            doSomething(new TestCallback() {
                @Override
                public void doCallback() {
                    throw new NullPointerException();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void doSomething(TestCallback callback){
        callback.doCallback();
    }

    interface TestCallback {
        public void doCallback();
    }
}

RESULT:
java.lang.NullPointerException
    at managers.concurrency.Test$1.doCallback(Test.java:11)
    at managers.concurrency.Test.doSomething(Test.java:20)
    at managers.concurrency.Test.main(Test.java:8)

在上面的代码中,我们将获得NullPointerException,因为回调代码在堆栈的不同部分执行。有没有办法在本地捕获这些例外?

1 个答案:

答案 0 :(得分:5)

您已经捕获了异常。尝试以下内容 -

    try {
        doSomething(new TestCallback()  {
            @Override
            public void doCallback()  {
                throw new NullPointerException();
            }
        });
    } catch (Exception e) {
        System.out.println("Exception caught !!!");
    }

输出:

Exception caught !!!