Null check or catching NullPointerException

java.lang.NullPointerException is the exception which is thrown when code tries to access member of the object using reference which is actually pointing to null.

ClassXYZ objRef = null;
objRef.getField();

So What should be done to properly handle such situation.

Approach 1

ClassXYZ objRef = new ClassXYZ();
objRef.setField(null);
if(objRef.getField() != null) {
   objRef.getField().getSubField();
}

Approach 2

ClassXYZ objRef = new ClassXYZ();
objRef.setField(null);
if(objRef.getField() != null) {
  objRef.getField().getSubField();
} else {
  LOGGER.error("Null Pointer Exception Occured"); 
}

Approach 3

ClassXYZ objRef = new ClassXYZ();
objRef.setField(null);
try {
  objRef.getField().getSubField();
} catch (NullPointerException ex) {
  LOGGER.error("Null Pointer Exception Occured");
}


Is it expected to have null for the Field. If Yes, Then we should put a null check so that no error is logged and it will just be ignored.

If we want some message to be logged, we can follow approach 2. Though It's a bad practice and should be avoided normally.

But If we want complete error trace to be logged or we want this handling to be thrown to caller , we should handle it as an exception.