What are the ways to solve and prevent null pointer exceptions in Java?

1 Introduction

In the process of Java development, we often encounter the troublesome problem of null pointer exception (NullPointerException). Null pointer exception is one of the most common errors in programs, which can lead to a series of problems such as program crashes and operation failures. This article will introduce in detail the method of solving null pointer exception in Java.

2. The cause of null pointer exception

A null pointer exception usually occurs when calling a method or property of an object whose value is null. For example, in the following code:

String str = null;
int length = str.length();

Since the value of the str object is null, a null pointer exception is thrown when its length method is called.

3. Methods to prevent null pointer exceptions

3.1 Check if the object is null

The most basic way to avoid null pointer exceptions is to perform a null check before using the object. For example, before using a String object, you can check whether it is null, such as:

String str = null;
if(str != null) {
    
    
    int length = str.length();
}

This way, its methods are not called when the object is null.

Similarly, when calling a method, you can also perform a null check on the method parameters first. For example, the following method takes a String object as a parameter:

public void process(String str) {
    
    
    if(str != null) {
    
    
        // 进行处理
    } else {
    
    
        // 抛出异常或返回错误信息
    }
}

3.2 Using the Optional class

Optional is a new feature added in Java 8. It is a container object that can wrap any type. An Optional object may contain null, or it may contain a type of non-null value, representing a value that may or may not be empty. Use it to avoid NullPointerException.

3.2.1 Creating Optional objects

We can use Optional.of(), Optional.empty() and Optional.ofNullable() methods to create Optional objects. The main difference between these methods is how they handle null values.

When using the Optional.of() method to create an Optional object, if the incoming parameter is null, a NullPointerException will be thrown. example:

String str = null;
Optional<String> optionalStr = Optional.of(str); //抛出NullPointerException异常

Use the Optional.empty() method to create an empty Optional object. example:

Optional<String> optionalStr = Optional.empty(); //创建空的Optional对象

Use the Optional.ofNullable() method to create an Optional object. If the incoming parameter is null, an empty Optional object is created. example:

String str = null;
Optional<String> optionalStr = Optional.ofNullable(str); //创建空的Optional对象

3.2.2 Using the Optional object

Use the isPresent() method to determine whether the Optional object contains a non-null value. Returns true if included, false otherwise. For example:

String str = "hello";
Optional<String> optionalStr = Optional.of(str);

if(optionalStr.isPresent()) {
    
    
    System.out.println(optionalStr.get()); //输出hello
}

Use the orElse() method to obtain the value in the Optional object. If the Optional object contains a non-empty value, return this value directly, otherwise return the default value passed in. example:

String str = null;
Optional<String> optionalStr = Optional.ofNullable(str);

String result = optionalStr.orElse("world");
System.out.println(result); //输出world

Use the orElseGet() method to get the value in the Optional object. If the Optional object contains a non-null value, return this value directly, otherwise return the default value generated by the Lambda expression. Unlike the orElse() method, the default value in the orElseGet() method is generated by a Lambda expression. For example:

String str = null;
Optional<String> optionalStr = Optional.ofNullable(str);

String result = optionalStr.orElseGet(() -> "world");
System.out.println(result); //输出world

Use the orElseThrow() method to get the value in the Optional object. If the Optional object contains a non-empty value, return this value directly, otherwise return the exception generated by the Lambda expression. example:

String str = null;
Optional<String> optionalStr = Optional.ofNullable(str);
String result = optionalStr.orElseThrow(() -> new RuntimeException("value not found"));

Use the ifPresent() method to perform specific actions if the Optional object contains a non-null value. example:

String str = "hello";
Optional<String> optionalStr = Optional.of(str);
optionalStr.ifPresent(System.out::println); //输出hello

Use the get() method to obtain the value in the Optional object. If the Optional object contains a non-empty value, return this value directly, otherwise throw NoSuchElementException. example:

String str = "hello";
Optional<String> optionalStr = Optional.of(str);

String result = optionalStr.get();
System.out.println(result); //输出hello

3.3 Using the Objects.requireNonNull method

In Java 7, the Objects class provides the requireNonNull method for null checking. The function of this method is to check whether the incoming parameter value is null, and if it is null, a NullPointerException will be thrown.

For example, here's an example using the requireNonNull method:

String str = null;
Objects.requireNonNull(str, "参数值不能为null");
int length = str.length();

In the above code, if str is null, a NullPointerException will be thrown with the specified error message. Of course, it is also possible not to specify an error message.

4. How to solve null pointer exception

4.1 Using the if statement

In code, using if statements to determine the null value is an effective way to avoid NullPointerException. In the code below:

String str = null;
if (str != null) {
    
    
    // 对str进行某些操作
}

If str is null, the if condition is not true, the code will not continue to execute, so there will be no NullPointerException.

4.2 Using the try-catch statement

In the code, using the try-catch statement to handle NullPointerException is an emergency method to avoid program crashes. In the code below:

try {
    
    
    String str = null;
    int length = str.length();
} catch (NullPointerException e) {
    
    
    e.printStackTrace();
    // 进行异常处理
}

If str is null, a NullPointerException will be thrown. At this point, the code in the try block stops executing and control of the program passes to the catch block. In the catch block, exceptions can be handled. In this way, the crash of the program can be avoided.

4.3 Using the ternary operator

In code, using the ternary operator is a straightforward way to avoid NullPointerException. In the code below:

String str = null;
int length = (str == null) ? 0 : str.length();

If str is null, assign length to 0; otherwise, call the str.length() method.

5. Summary

Null pointer exception is a problem that is easy to encounter in the program. In order to avoid this problem, we should try to avoid using null values ​​in the code. If you must use a null value, you should perform a null check before using it. This article describes ways to prevent and resolve null pointer exceptions, including checking whether an object is null, using the Optional class, using the Objects.requireNonNull method, using if statements, using try-catch statements, and using ternary operators. When writing code, you can choose to use one or more methods according to the actual situation to improve the error tolerance and readability of the code.

Guess you like

Origin blog.csdn.net/ly1347889755/article/details/130255056