user2902067
user2902067

Reputation: 75

Exception Handling with Null return

I have a Java Class which does JNDI lookup and returns lookup ejb object. And if there is failure in lookup various exceptions are handled, when there is failure it will return null.

Now when that API is called and lookup fails we will get nullpointer exception. We can do a null check in calling class but I need exact reason for failure .. How to catch those exceptions thrown in base class?

Upvotes: 0

Views: 126

Answers (2)

Klas Lindbäck
Klas Lindbäck

Reputation: 33273

If you want to transfer error information upwards in the call chain, the best way to do that is with an exception.

Instead of returning null on a failed look-up you should either let the look-up exception propagate up or wrap it in a custom exception if you want to add additional information.

Upvotes: 1

Jean Logeart
Jean Logeart

Reputation: 53819

Don't catch exceptions or if you need to catch them to do some specific work, rethrow them when done so the caller can see there was an exception and handle it itself too.

Like:

method1() {
    try {
        // SomeException is thrown here
    } catch (SomeException e) {
        // do some work because of the exception
        throw e // re-throw or throw new MyException(e)
    }
}

method2() {
    try {
        method1();
    } catch (SomeException e) {
        // something went bad! 
        // do some specific work?
    }
}

Upvotes: 1

Related Questions