Reading:
Prevent Null Pointer Exception

Prevent Null Pointer Exception

Metamug
Prevent Null Pointer Exception

Not Null Check in Java

It is common in java to check for Not Null before performing an operation to avoid NullPointerException.

Object result = someOperation();
if(result != null){
    //use the object
    result.toString(); 
}

Throw Exception if Cannot Handle

It is mandatory to initialize a local variable. We start off with assigning it to null. The default try-catch block generated by the IDEs does not assign the object.

public Object someOperation(){   
    Object obj = null;   
    try{        
        obj =  someOtherOperation()   
    }catch(BusinessException e){      
        e.printStackTrace()   
    }   
    return obj;
}

Object result = someOperation();

if(result != null){
    //use the object
    result.toString(); 
}

The catch clause SHOULD assign the object, if it cannot do that. There is no need of the try-catch block here. Use try catch only if you can handle the exception

public Object someOperation() throws BusinessException{   
    Object obj =  someOtherOperation();
}

try{
    Object result = someOperation();
    result.toString();
}catch(BusinessException e){
    //Write some business logic to handle the business exception.
}

The line result.toString() will never throw NullPointerException because it will throw a BusinessException on the previous line.

Here the method doesn't return a null value at all. It will either return a valid object or throw a BusinessException. Code that handles the BusinessException MUSt know what is to be done with the exception.

Always initialize a Collection.

if (list != null && !list.isEmpty()) {
    for (int i = 0; i < list.size(); i++) {
       //TODO
    }
}

Lists should never be checked for null. They should be initialized when they are declared.

The below loop will fail for an empty collection.

for (Object obj: list) {
    //TODO
}

Sending empty list instead of Null object helps reduce null check. Assign Empty Collection in catch block in case handling exceptions

NullObject Pattern

NullObject Pattern

NullObject pattern describes to inherit the class and implement default behavior in case of null. So calling methods of the NullObject will result in consistent behaviour.



Icon For Arrow-up
Comments

Post a comment