java.lang.NullPointerException
java.lang.NullPointerException is one of the most popular exceptions in java programming. Anybody working in java must have seen this popping out of nowhere in java standalone program as well as java
java.lang.NullPointerException is one of the most popular exceptions in java programming. Anybody working in java must have seen this popping out of nowhere in java standalone program as well as java web application.
java.lang.NullPointerException是Java编程中最流行的异常之一 。 在Java中工作的任何人都必须在Java独立程序和Java Web应用程序中看到这种突然出现的现象。
java.lang.NullPointerException (java.lang.NullPointerException)
NullPointerException is a runtime exception, so we don’t need to catch it in program. NullPointerException is raised in an application when we are trying to do some operation on null where an object is required. Some of the common reasons for NullPointerException in java programs are;
NullPointerException是运行时异常,因此我们不需要在程序中捕获它。 当我们尝试在需要对象的null上执行某些操作时,会在应用程序中引发NullPointerException。 Java程序中NullPointerException的一些常见原因是:
- Invoking a method on an object instance but at runtime the object is null. 在对象实例上调用方法,但在运行时该对象为null。
- Accessing variables of an object instance that is null at runtime. 在运行时访问为null的对象实例的变量。
- Throwing null in the program 在程序中抛出null
- Accessing index or modifying value of an index of an array that is null 访问为空的数组的索引或修改索引的值
- Checking length of an array that is null at runtime. 检查在运行时为null的数组的长度。
Java NullPointerException示例 (Java NullPointerException Example)
Let’s look at some examples of NullPointerException in java programs.
让我们看一下Java程序中NullPointerException的一些示例。
-
调用实例方法时发生NullPointerException (NullPointerException when calling instance method)
public class Temp { public static void main(String[] args) { Temp t = initT(); t.foo("Hi"); } private static Temp initT() { return null; } public void foo(String s) { System.out.println(s.toLowerCase()); } }
When we run above program, it throws following NullPointerException error message.
We are getting NullPointerException in statement
t.foo("Hi");
because “t” is null here.public class Temp { public static void main(String[] args) { Temp t = initT(); t.foo("Hi"); } private static Temp initT() { return null; } public void foo(String s) { System.out.println(s.toLowerCase()); } }
当我们在上面的程序上运行时,它引发以下NullPointerException错误消息。
我们在语句
t.foo("Hi");
中获得NullPointerExceptiont.foo("Hi");
因为这里的“ t”为空。 -
Java NullPointerException,同时访问/修改空对象的字段 (Java NullPointerException while accessing/modifying field of null object)
public class Temp { public int x = 10; public static void main(String[] args) { Temp t = initT(); int i = t.x; } private static Temp initT() { return null; } }
Above program throws following NullPointerException stack trace.
NullPointerException is being thrown in statement
int i = t.x;
because “t” is null here.public class Temp { public int x = 10; public static void main(String[] args) { Temp t = initT(); int i = t.x; } private static Temp initT() { return null; } }
上面的程序将引发以下NullPointerException堆栈跟踪。
在语句
int i = tx;
抛出NullPointerExceptionint i = tx;
因为这里的“ t”为空。 -
在方法参数中传递null时,Java NullPointerException (Java NullPointerException when null is passed in method argument)
public class Temp { public static void main(String[] args) { foo(null); } public static void foo(String s) { System.out.println(s.toLowerCase()); } }
This is one of the most common occurrence of
java.lang.NullPointerException
because it’s the caller who is passing null argument.Below image shows the null pointer exception when above program is executed in Eclipse IDE.
public class Temp { public static void main(String[] args) { foo(null); } public static void foo(String s) { System.out.println(s.toLowerCase()); } }
这是
java.lang.NullPointerException
最常见的情况之一,因为它是传递null参数的调用方。 -
引发null时java.lang.NullPointerException (java.lang.NullPointerException when null is thrown)
public class Temp { public static void main(String[] args) { throw null; } }
Below is the exception stack trace of above program, showing NullPointerException because of
throw null;
statement.public class Temp { public static void main(String[] args) { throw null; } }
下面是上述程序的异常堆栈跟踪,显示由于
throw null;
而导致的NullPointerExceptionthrow null;
声明。 -
获取空数组的长度时,java.lang.NullPointerException (java.lang.NullPointerException when getting length of null array)
public class Temp { public static void main(String[] args) { int[] data = null; int len = data.length; } }
public class Temp { public static void main(String[] args) { int[] data = null; int len = data.length; } }
-
访问null数组的索引值时发生NullPointerException (NullPointerException when accessing index value of null array)
public class Temp { public static void main(String[] args) { int[] data = null; int len = data[2]; } }
public class Temp { public static void main(String[] args) { int[] data = null; int len = data[2]; } }
-
在null对象上同步时java.lang.NullPointerException (java.lang.NullPointerException when synchronized on null object)
public class Temp { public static String mutex = null; public static void main(String[] args) { synchronized(mutex) { System.out.println("synchronized block"); } } }
synchronized(mutex)
will throw NullPointerException because “mutex” object is null.synchronized(mutex)
将抛出NullPointerException,因为“ mutex”对象为null。 -
HTTP状态500 java.lang.NullPointerException (HTTP Status 500 java.lang.NullPointerException)
-
Sometimes we get an error page being sent as java web application response with error message as “HTTP Status 500 – Internal Server Error” and root cause as
java.lang.NullPointerException
.有时,我们会以Java Web应用程序响应的形式发送错误页面,错误消息为“ HTTP Status 500 – Internal Server Error”,根本原因为
java.lang.NullPointerException
。For this I edited the Spring MVC Example project and changed the HomeController method as below.
为此,我编辑了Spring MVC Example项目并更改了HomeController方法,如下所示。
@RequestMapping(value = "/user", method = RequestMethod.POST) public String user(@Validated User user, Model model) { System.out.println("User Page Requested"); System.out.println("User Name: "+user.getUserName().toLowerCase()); System.out.println("User ID: "+user.getUserId().toLowerCase()); model.addAttribute("userName", user.getUserName()); return "user"; }
Below image shows the error message thrown by web application response.
下图显示了Web应用程序响应抛出的错误消息。
Here is the exception stack trace;
这是异常堆栈跟踪;
HTTP Status 500 – Internal Server Error Type Exception Report Message Request processing failed; nested exception is java.lang.NullPointerException Description The server encountered an unexpected condition that prevented it from fulfilling the request. Exception org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982) org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) javax.servlet.http.HttpServlet.service(HttpServlet.java:661) org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) javax.servlet.http.HttpServlet.service(HttpServlet.java:742) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) Root Cause java.lang.NullPointerException com.journaldev.spring.controller.HomeController.user(HomeController.java:38) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:498)
Root cause is NullPointerException in statement
user.getUserId().toLowerCase()
becauseuser.getUserId()
is returning null.根本原因是语句
user.getUserId().toLowerCase()
NullPointerException,因为user.getUserId()
返回null。
如何检测java.lang.NullPointerException (How to detect java.lang.NullPointerException)
Detecting NullPointerException is very easy, just look at the exception trace and it will show you the class name and line number of the exception. Then look at the code and see what could be null causing the NullPointerException. Just look at all the above examples, it’s very clear from stack trace what is causing null pointer exception.
检测NullPointerException非常容易,只需查看异常跟踪,它就会为您显示异常的类名和行号。 然后查看代码,看看可能为null导致NullPointerException的情况。 只要看一下以上所有示例,就可以从堆栈跟踪中非常清楚是什么导致了空指针异常。
如何修复java.lang.NullPointerException (How to fix java.lang.NullPointerException)
java.lang.NullPointerException is an unchecked exception, so we don’t have to catch it. Usually null pointer exceptions can be prevented using null checks and preventive coding techniques. Look at below code examples showing how to avoid java.lang.NullPointerException
.
java.lang.NullPointerException是未经检查的异常,因此我们不必捕获它。 通常,可以使用空检查和预防性编码技术来防止空指针异常。 查看下面的代码示例,这些示例显示如何避免java.lang.NullPointerException
。
if(mutex ==null) mutex =""; //preventive coding
synchronized(mutex) {
System.out.println("synchronized block");
}
//using null checks
if(user!=null && user.getUserName() !=null) {
System.out.println("User Name: "+user.getUserName().toLowerCase());
}
if(user!=null && user.getUserName() !=null) {
System.out.println("User ID: "+user.getUserId().toLowerCase());
}
编码最佳实践,以避免java.lang.NullPointerException (Coding Best Practices to avoid java.lang.NullPointerException)
- Consider a code example below.
public void foo(String s) { if(s.equals("Test")) { System.out.println("test"); } }
Now NullPointerException can occur if the argument is being passed as null. Same method can be written as below to avoid NullPointerException.
考虑下面的代码示例。public void foo(String s) { if(s.equals("Test")) { System.out.println("test"); } }
现在,如果将参数作为null传递,则可能发生NullPointerException。 可以如下编写相同的方法来避免NullPointerException。
- We can also add null check for argument and throw
IllegalArgumentException
if required.
我们还可以为参数添加null检查,并在需要时抛出public int getArrayLength(Object[] array) { if(array == null) throw new IllegalArgumentException("array is null"); return array.length; }
IllegalArgumentException
。 - Use ternary operator as shown in below example code.
如以下示例代码所示,使用三元运算符。String msg = (str == null) ? "" : str.substring(0, str.length()-1);
- Use
String.valueOf()
rather thantoString()
method. For example check PrintStream println() method code is defined as below.public void println(Object x) { String s = String.valueOf(x); synchronized (this) { print(s); newLine(); } }
So below shows the example where valueOf() method is used instead of toString().
使用String.valueOf()
而不是toString()
方法。 例如,检查PrintStream println()方法的代码定义如下。public void println(Object x) { String s = String.valueOf(x); synchronized (this) { print(s); newLine(); } }
因此,下面显示了使用valueOf()方法代替toString()的示例。
- Write methods returning empty objects rather than null wherever possible, for example empty list, empty string etc. 编写返回空对象而不是null的方法,例如空列表,空字符串等。
- There are some methods defined in collection classes to avoid NullPointerException, use them. For example contains(), containsKey() and containsValue(). 集合类中定义了一些方法来避免NullPointerException,请使用它们。 例如contains(),containsKey()和containsValue()。
That’s all about java NullPointerException. I hope it will help you in writing better code to avoid java.lang.NullPointerException
as much as possible.
这就是关于Java NullPointerException的全部。 我希望它可以帮助您编写更好的代码,从而尽可能避免java.lang.NullPointerException
。
Reference: API Document
参考: API文档
翻译自: https://www.journaldev.com/14544/java-lang-nullpointerexception
更多推荐
所有评论(0)