The handling of null pointer exceptions in Java code

  • 2020-04-01 01:36:33
  • OfStack

There are two nullpointerexceptions encountered in projects:

1. Refer to the empty object, that is, call the methods of the empty object or refer to the properties of the empty object.

2. Assign the wrapper class of the base type in 8 to the corresponding base class.

 

1. Non-null judgment should be made on the returned object of others' interface, because it is not clear whether the acquired object will be null. For Collection Map, I will generally call CollectionUtils MapUtils, and for the returned String object, I will call stringutils.isnotempty () for non-null judgment. Among them, isNotEmpty determines not only NULL but also an empty set and an empty string. For example, query results from data. The pricing URL returned in the workflow

2 for their own creation of the object, to pay attention to what the object operation, the middle will not cause the object to be empty, if it is possible to add non-empty judgment, especially for the operation of the set, it is easy to declare a null pointer!! So I take great care every time I set up an operation.

3. Be very careful about the foreground domain objects, because these objects are created by the framework. If I did not enter a value in the text box of the foreground, the background will get an empty string when I submit, but the probability of NullPointerException is high.

4. Try to use apache's StringUtils class for String operations, which is very safe compared with String. For collection operations, apache's CollectionUtils and MapUtils are used, which are also very efficient compared with apache utility classes, such as stringutils.split ().

Some people say that too much judgment can affect performance, and I personally think the performance sacrifice here is trivial compared to the security of the system.


Related articles: