[Java] NullPointerException in exception handling

Of all RuntimeExceptionthe exceptions, Java programmers are probably most familiar with NullPointerExceptionthem .

NullPointerExceptionThat is, a null pointer exception, commonly known as NPE. If an object is null, calling its method or accessing its fields will result NullPointerException, this exception is usually JVMthrown by, for example:

// NullPointerException
public class Main {
    
    
    public static void main(String[] args) {
    
    
        String s = null;
        System.out.println(s.toLowerCase());
    }
}

The concept of pointers actually comes from the C language, and there are no pointers in the Java language. The variables we define are actually references, Null Pointermore precisely Null Reference, but there is not much difference between the two.

deal withNullPointerException

If so NullPointerException, how should we deal with it? First of all, it must be clear that NullPointerExceptionit is a code logic error. When encountered NullPointerException, the principle is to expose it early and fix it early. It is strictly forbidden to use catch to hide this coding error:

// 错误示例: 捕获NullPointerException
try {
    
    
    transferMoney(from, to, amount);
} catch (NullPointerException e) {
    
    
}

Good coding practices can greatly reduce NullPointerExceptionthe production of, for example:

Member variables are initialized at definition time:

public class Person {
    
    
    private String name = "";
}

Using an empty string "" instead of the default null can avoid a lot NullPointerException. When writing business logic, using an empty string "" to indicate that it is not filled is much safer than null.

Return an empty string "", an empty array instead of null:

public String[] readLinesFromFile(String file) {
    
    
    if (getFileSize(file) == 0) {
    
    
        // 返回空数组而不是null:
        return new String[0];
    }
    ...
}

This saves the caller from having to check whether the result is null.

If the caller must judge based on null, such as returning null to indicate that the file does not exist, then consider returning Optional:

public Optional<String> readFromFile(String file) {
    
    
    if (!fileExist(file)) {
    
    
        return Optional.empty();
    }
    ...
}

In this way, the caller must pass Optional.isPresent()the judgment whether there is a result.

Locating NullPointerException

If it occurs NullPointerException, for example, when calling abcx() NullPointerException, the reason may be:

a is null;
ab is null;
abc is null;
before determining which object is null, only such logs can be printed:

System.out.println(a);
System.out.println(a.b);
System.out.println(a.b.c);

Starting from Java 14, if it is generated NullPointerException, the JVM can give detailed information to tell us who the null object is. Let's look at an example:

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Person p = new Person();
        System.out.println(p.address.city.toLowerCase());
    }
}

class Person {
    
    
    String[] name = new String[2];
    Address address = new Address();
}

class Address {
    
    
    String city;
    String street;
    String zipcode;
}

You can NullPointerExceptionsee something like is null in the detailed information ... because "<local1>.address.city" , which means that the city field is null, so that we can quickly locate the problem.

The detailed information of this enhancement NullPointerExceptionis a new feature of Java 14, but it is turned off by default. We can add a - XX:+ShowCodeDetailsInExceptionMessagesparameter to the JVM to enable it:

java -XX:+ShowCodeDetailsInExceptionMessages Main.java

summary

NullPointerExceptionIt is a common logic error in Java code, which should be exposed and repaired early;

You can enable Java 14's enhanced exception information to view NullPointerExceptiondetailed error information.

Guess you like

Origin blog.csdn.net/ihero/article/details/132189662