If you have spent some time developing programs in Java, at some point you have definitely seen the following exception:
如果您花了一些时间使用Java开发程序,那么在某些时候您肯定会看到以下异常:
java.lang.NullPointerExceptionSome major production issues arise due to NullPointerException. In this article, we'll go over some ways to handle NullPointerException in Java.
由于NullPointerException出现了一些主要的生产问题。 在本文中,我们将介绍一些在Java中处理NullPointerException方法。
(Simple Null Check)
Consider the following piece of code:
考虑以下代码:
public static void main(String args[]) {
String input1 = null;
simpleNullCheck(input1);
}
private static void simpleNullCheck(String str1) {
System.out.println(str1.length());
}If you run this code as is, you will get the following exception:
如果按原样运行此代码,则会出现以下异常:
Exception in thread "main" java.lang.NullPointerExceptionThe reason you are getting this error is because we are trying to perform the length() operation on str1 which is null.
您收到此错误的原因是因为我们正在尝试执行length() 对str1操作,该操作为null 。
An easy fix for this is to add a null check on str1 as shown below:
一个简单的解决方法是在str1上添加一个空检查 如下所示:
private static void simpleNullCheck(String str1) {
if (str1 != null) {
System.out.println(str1.length());
}
}This will ensure that, when str1 is null, you do not run the length() function on it.
这将确保在str1 是 null ,您不运行length() 功能就可以了。
But you may have the following question.
但是您可能有以下问题。
(What if str1 is an important variable?)
In that case you can try something like this:
在这种情况下,您可以尝试如下操作:
private static void simpleNullCheck(String str1) {
if (str1 != null) {
System.out.println(str1.length());
} else {
// Perform an alternate action when str1 is null
// Print a message saying that this particular field is null and hence the program has to stop and cannot continue further.
}
}The idea is that, when you expect a value to be null, its better to put a null check on that variable. And if the value does turn out to be null, take an alternative action.
这个想法是,当您期望一个值是null ,最好对该变量进行null检查。 并且如果该值确实为null ,请采取替代措施。
This is applicable not only to strings, but to any other object in Java.
这不仅适用于字符串,而且适用于Java中的任何其他对象。
(Lombok Null Check)
Now take the following example:
现在来看下面的例子:
public static void main(String args[]) {
String input2 = "test";
List<String> inputList = null;
lombokNullCheck(input2, inputList, input2);
}
public static void lombokNullCheck(String str1, List<String> strList, String str2) {
System.out.println(str1.length() + strList.size() + str2.length());
}Here we have a function that accepts three arguments: str1, strList, and str2.
在这里,我们有一个接受三个参数的函数: str1 , strList和str2 。
If any of these values turn out to be null, we do not want to execute the logic in this function at all.
如果这些值中的任何一个为null ,我们根本就不想执行此函数中的逻辑。
(How do you achieve this?)
This is where Lombok comes handy. In order to add the Lombok library in your code, include the following Maven dependency:
这是Lombok派上用场的地方。 为了在您的代码中添加Lombok库,请包括以下Maven依赖项:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>To learn more about Maven, check out this article.
要了解有关Maven的更多信息,请查看本文 。
Here's what the code would look like with the Lombok null check:
Lombok null检查的代码如下所示:
public static void main(String args[]) {
String input2 = "test";
List<String> inputList = null;
try {
lombokNullCheck(input2, inputList, input2);
} catch (NullPointerException e) {
System.out.println(e);
}
}
public static void lombokNullCheck(@NonNull String str1, @NonNull List<String> strList, @NonNull String str2) {
System.out.println(str1.length() + strList.size() + str2.length());
}Before every argument of the function we add @NonNull annotation.
在函数的每个参数之前,我们添加@NonNull 注解。
Also when we call this function, we put a try-catch block around the function call to catch NullPointerException.
同样,当我们调用此函数时,我们在函数调用周围放置了一个try-catch块来捕获NullPointerException 。
If any of the arguments given in the function turn out to be null, the function would throw a NullPointerException. This would then be caught by the try-catch block.
如果函数中给定的任何参数为null ,则该函数将抛出NullPointerException 。 然后,这将被try-catch块try-catch 。
This ensures that, if any of the function arguments turn out to be null, then the logic in the function is not executed and we know the code won't behave unusually.
这样可以确保,如果任何函数参数证明为null ,那么函数中的逻辑将不会执行,并且我们知道代码不会表现异常。
This can be done with a bunch of null check statements as well. But using Lombok helps us avoid writing multiple null check statements and makes the code look much cleaner.
这也可以用一堆null检查语句来完成。 但是使用Lombok可以帮助我们避免编写多个null检查语句,并使代码看起来更简洁。
(Lists and Nulls)
Say that you have a list and you want to print all elements in the list:
假设您有一个列表,并且要打印列表中的所有元素:
List<String> stringList = new ArrayList<>();
stringList.add("ele1");
stringList.add("ele2");
if (stringList != null) {
for (String element : stringList)
System.out.println(element);
}Before looping over the list, we need to put a null check on the list.
在遍历列表之前,我们需要对列表进行null检查。
If the null check is not present, then trying to loop over a null list will throw a NullPointerException.
如果不存在null检查,则尝试循环遍历null列表将引发NullPointerException 。
(Maps and Nulls)
Let's take the scenario where you need to access the value for a particular key in a map:
让我们假设需要访问映射中特定键的值的场景:
Map<String, String> testMap = new HashMap<>();
testMap.put("first_key", "first_val");
if (testMap != null && testMap.containsKey("first_key")) {
System.out.println(testMap.get("first_key"));
}First we need to do a null check on the map object itself. If this is not done, and the map is null, then a NullPointerException is thrown. This is done using testMap!=null
首先,我们需要对地图对象本身进行null检查。 如果未完成,并且映射为null ,则抛出NullPointerException 。 这是使用testMap!=null
Once that is done, check if a particular key is present before accessing it. You can check the presence of the key using testMap.containsKey("first_key"). If this is not done and the particular key is absent, then you will get the value as null.
完成此操作后,在访问前检查是否存在特定的密钥。 您可以使用testMap.containsKey("first_key")检查密钥的存在。 如果不这样做,并且缺少特定的键,那么您将获得值为null的值。
(Is it necessary to always add a Null Check?)
If you know for certain that a particular variable can never be null, then you can avoid adding the null check. This maybe applicable in private functions where you can control the data going into function.
如果您确定某个特定变量永远不会为null ,则可以避免添加null检查。 这可能适用于私有功能,您可以在其中控制数据进入功能。
But if you are not really certain about the nullability of an object, it is best to add a null check.
但是,如果您不确定某个对象的可为空性,则最好添加一个null检查。
码 (Code)
All the code discussed in this article can be found in this Github repo.
在Github存储库中可以找到本文讨论的所有代码。
恭喜😊 (Congrats 😊)
You now know how handle NullPointerException in Java!
您现在知道了如何在Java中处理NullPointerException !
















