Null Pointer exception is the most common and annoying exception. This topic describes how to avoid NULL pointer exceptions.
First, let's look at the following example
private Boolean isFinished(String status) { if (status.equalsIgnoreCase("Finish")) { return Boolean.TRUE; } else { return Boolean.FALSE; } }
If the value of status is null, a null pointer exception will occur (row 2nd in this example ). Therefore, we should use the following method:
private Boolean isFinished(String status) { if ("Finish".equalsIgnoreCase(status)) { return Boolean.TRUE; } else { return Boolean.FALSE; } }
In this case, if the status is empty, no NULL pointer exception will occur. I believe most of our friends already know this method. If an object may be null, you do not need to call it directly.
Next, I will provide several suggestions to avoid null pointers.
1. Check whether the collection is empty.
2. Use some judgment methods.
3. Assert keyword.
4. Assert class.
5. Exception Handling.
6. Too many vertices. Operation syntax.
7. Use the stringutils class
1. Check whether the collection is empty.
If the collection is empty, no element exists in the collection. Some developers often return null when there are no elements in the collection. A better way is to return collections. empty_list, collections. empty_set or collections. empty_map.
Error Code
public static List getEmployees() { List list = null; return list; }
Correct code
public static List getEmployees() { List list = Collections.EMPTY_LIST; return list; }
2. Use some judgment methods
Use methods such as contains (), indexof (), isempty (), containskey (), containsvalue, and hasnext () to determine whether null values exist.
Example:
String myName = "qiyadeng"; 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();
3. Assert keywords
After Java, assert is provided to determine the assumptions in your code. The syntax is as follows:
assert expression1
Expression1 is a Boolean expression. If expression1 returns false, the system will throw asserterror (no details ).
Another method
assert expression1:expression2
If expression1 returns false, the system will throw asserterror and the detailed information is expression2.
Example:
public static String getManager(String employeeId) { assert (employeeId != null) : "employeeId must be not null"; return "qiyadeng"; }
I use getmanager (null) to call the getmanger method. The final running result is "Java. Lang. assertionerror: employeedid must be not null"
Remember to add-enableassertion to the Java option to enable the assertion function.
4. Assert class
The assert class has many methods in the com. Bea. Core. repackaged. springframework. util package for assertions.
public static String getManager(String employeeId) { Assert.notNull(employeeId, "employeeId must be not null"); Assert.hasLength(employeeId, "employeeId must has length greater than 0"); return "qiyadeng"; }
When getmanager (null) is also used to call the getmanager method, the information "Java. Lang. illegalargumentexception: employeeid must be not null" will be obtained ".
5. Exception Handling
Use try catch to handle exceptions or check whether the variables are empty.
public static String getManager(String employeeId) { return null; }
The above code is called using the following method:
String managerId = getManager("A015"); System.out.println(managerId.toString());
"Java. Lang. nullpointerexception" will occur. To handle this exception, we should use try catch to handle the exception or check whether the variable is null.
Try-Catch Method
String managerId = getManager("A015"); try { System.out.println(managerId.toString()); } catch (NullPointerException npe) { //write your code here }
Or check the variables.
String managerId = getManager("A015"); if (managerId != null) { System.out.println(managerId.toString()); } else { //write your code here }
6. do not have too many points. Operation syntax
Some developers use too many such methods to reduce code, but this is not good for subsequent maintenance and exception handling.
Incorrect syntax
String attrValue = (String)findViewObject("VO_NAME").getCurrentRow().getAttribute("Attribute_NAME");
Correct writing
ViewObject vo = findViewObject("VO_NAME"); Row row = vo.getCurrentRow(); String attrValue = (String)row.getAttribute("Attribute_NAME");
7. Use the stringutils class
Stringutil is a class in the org. Apache. commns. lang package. We can use this class to avoid NULL pointer exceptions.
For example, stringutils. isempty (), stringutils. isblank, stringutils. Equals (), and so on. For more information, see the documentation.
To avoid NULL pointer exceptions, you must always check whether your code will throw nullpointerexception during code writing. If you do not have time to adjust it, use the // todo flag, this helps you solve the problem later.
Original article, reprinted Please note:Reprinted from http://www.qiyadeng.com/
Link:Avoid NULL pointer exceptions in Java (NULL pointer exception)