Of all the RuntimeException
exceptions, Java programmers are probably most familiar with NullPointerException
.
NullPointerException
is the null pointer exception, commonly known as NPE. This exception is usually thrown by the JVM if an object is null
called, its methods are called or its fields are accessed , for example:NullPointerException
1 2 3 4 5 6 7 8 9 |
// NullPointerException ---- public class Main { public static void main(String[] args) { String s = null; System.out.println(s.toLowerCase()); } } |
The concept of pointers is actually derived from the C language, and there are no pointers in the Java language. The variables we define are actually references, Null Pointer is more precisely Null Reference, but the difference between the two is not much.
Handling NullPointerException
If encountered NullPointerException
, how should we deal with it? First of all, it must be clear that it NullPointerException
is a code logic error. When encountered NullPointerException
, follow the principle of early exposure and early repair. It is strictly prohibited to use catch
to hide such coding errors:
1 2 3 4 5 6 |
// 错误示例: 捕获NullPointerException try { transferMoney(from, to, amount); } catch (NullPointerException e) { } |
Good coding practices can greatly reduce NullPointerException
the occurrence of, for example:
Member variables are initialized when they are defined:
1 2 3 4 |
public class Person { private String name = ""; } |
A lot can be avoided by using an empty string ""
instead of the default , and when writing business logic, it is much safer to use an empty string for unfilled .null
NullPointerException
""
null
Returns an empty string ""
, an empty array instead of null
:
1 2 3 4 5 6 7 8 |
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 make null
judgments, such as returning to null
indicate that the file does not exist, then consider returning Optional<T>
:
1 2 3 4 5 6 7 |
public Optional<String> readFromFile(String file) { if (!fileExist(file)) { return Optional.empty(); } ... } |
In this way, the caller must pass the Optional.isPresent()
judgment whether there is a result.
Locating NullPointerException
If generated NullPointerException
, for example, a.b.c.x()
when called, the NullPointerException
reason may be:
a
yesnull
;a.b
yesnull
;a.b.c
yesnull
;
Determining exactly which object was null
previously only able to print logs like this:
1 2 3 4 |
System.out.println(a); System.out.println(a.b); System.out.println(a.b.c); |
Starting from Java 14, if generated NullPointerException
, the JVM can give detailed information to tell us null
who the object is. Let’s look at an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
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 NullPointerException
see similar in the details of ... because "<local1>.address.city" is null
, meaning the city
field is null
, so we can quickly locate the problem.
This enhanced NullPointerException
detail is new in Java 14, but is off by default, we can -XX:+ShowCodeDetailsInExceptionMessages
enable it by adding a parameter to the JVM:
1 2 |
java -XX:+ShowCodeDetailsInExceptionMessages Main.java |
summary
NullPointerException
It is a common logic error in Java code, which should be exposed and repaired early;
NullPointerException
Detailed error information can be viewed by enabling Java 14’s Enhanced Exception Information.