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