4
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,因为回调代码是在堆栈的不同部分执行的。有没有办法在本地捕获此类异常?

4

1 回答 1

5

您已经捕获了异常。尝试如下 -

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

输出:

捕捉到异常!!!
于 2012-10-30T23:37:30.293 回答