How to Effectively Handle NullPointerException in Java
ans:-NullPointerException is an unchecked exception and extends RuntimeException.
It doesn’t force you to use catch block to handle it
Q-Why NullPointerException occur in your code?
ans-"NullPointerException is a situation in code where you try to access/ modify an object which has not been initialized yet"
means that object reference variable is not pointing anywhere and refers to nothing or ‘null’.
A simple example can be:
package com.piyush.npe; public class SampleNPE { public static void main(String[] args) { String s = null ; System.out.println(s.toString()); // s is un-initialized and is null } }
|
4:-)Use some Method
Use some methods to assure that null value not exist like contains(), indexOf(), isEmpty(), containsKey(), containsValue() and hasNext().
example:-
example2:-
String myName = "Piyush Kumar Bangalore";
List list = Collections.EMPTY_LIST;
boolean exist = list.contains(myName);
int index = list.indexOf(myName);
boolean isEmpty =list.isEmpty();
Map map =Collections.EMPTY_MAP;
exist=map.containsKey(myName);
exist=map.containsValue(myName);
isEmpty=map.isEmpty();
Set set=Collections.EMPTY_SET;
exist=set.contains(myName);
isEmpty=set.isEmpty();
Iterator iterator;
exist = iterator.hasNext();
5:-)Exception Handling:-
example:-a- try catch statement
I will change calling code to below code
b- Checking of Null values
I will change calling code to below code
6:-) StringUtils Class
StringUtils class is part of org.apache.commons.lang package, I can use it to avoid NPE specially all its methods are null safe
For example StringUtils. IsEmpty(), StringUtils. IsBlank(), StringUtils.equals(), and much more.
examle:-You can make use of the
and methods, in order to avoid the . For example:
7:-)assert Keyword
8-:) Assert Class
second way:-
How to solve a NullPointerException in Java?
It is simple, put a null check! Surround your object with if statement like
Object mayBeNullObj = getTheObjectItMayReturnNull();
if (mayBeNullObj != null) { // to avoid NullPointerException
mayBeNullObj.workOnIt();
}
if (mayBeNullObj != null) { // to avoid NullPointerException
mayBeNullObj.workOnIt();
}
No comments:
Post a Comment