Handling Null situations within NPE catch

classic Classic list List threaded Threaded
2 messages Options
J1234 J1234
Reply | Threaded
Open this post in threaded view
|

Handling Null situations within NPE catch

Which of the following way to deal in case of null objects is better from code review perspective and Why.

For example

Try {

System.out.println(obj1.obj2.obj3.obj4);

} catch ( NullPointerException ex ) {

System.out.println("Object1 not created properly");

}

or

If(obj1 == null || obj2 == null || obj3== null || obj4 == null){

System.out.println("Object1 not created properly");

}

John John
Reply | Threaded
Open this post in threaded view
|

Re: Handling Null situations within NPE catch

We should have a null check if that's expected in few cases as Throwing exception has a cost. Moreover additional Exception trace in log doesn't make any sense as the scenario is an expected one and hence doesn't need any investigation.

If there is a situation where getting null means application flaw, we should let application throw NPE as we would need trace for investigating the issue.