pvllnspk
pvllnspk

Reputation: 5767

try-catch arround callback

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)

In the above code we will get NullPointerException because the callback code is executed in the different part of stack. Is there a way to catch the such exceptions locally?

Upvotes: 4

Views: 3228

Answers (1)

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

You are already catching the exception. Try something as follows -

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

Output:

Exception caught !!!

Upvotes: 6

Related Questions