大家好,我是你的好朋友思创斯。今天说一说java.lang.nullpointerexception出现的几种原因及金沙1005的解决方案,希望您对编程的造诣更进一步.
java.lang.nullpointerexception
是java编程中最常见的异常之一。任何使用java的人都有在java程序以及java web应用程序中看到java.lang.nullpointerexception
异常。
nullpointerexception
是一个运行时异常,因此不需要在程序中捕获它。
当尝试在null
对象上执行某些操作时,会在应用程序中引发nullpointerexception
异常。以下是在java程序中发生nullpointerexception
异常的一些常见原因 –
- 在对象实例上调用方法,但在运行时对象为
null
。 - 访问在运行时为
null
的对象实例的变量。 - 在程序中抛出
null
。 - 访问索引或修改索引的数组为
null
。 - 检查在运行时为
null
的数组的长度。
在java编程中,nullpointerexception是一个常见的运行时异常,其发生原因可能包括:
避免java编程中nullpointerexception异常的方法包括:
1. 初始化字符串变量。
2. 使用具体的类对接口类型的对象进行初始化。
3. 在对象为空时进行判空处理。
4. 避免将null值用于字符串比较。
5. 使用string.valueof()方法代替tostring()方法以避免引用为null时抛出nullpointerexception异常。
6. 实例化class类型对象后再进行调用。
7. 返回值可以定义为数组,以避免返回null值引起nullpointerexception异常。
因此,我们在编程中应该尽量避免出现以上的情况,保证程序的健壮性和稳定性。对于不可避免的情况,我们应该进行判空处理,或者采用安全的编程习惯,以确保代码的正确性和稳定性。
nullpointerexception是java中的一个运行时异常,它通常发生在尝试访问空引用(即未分配内存空间的变量)的情况下。当你尝试对一个空对象进行操作时,程序就会抛出nullpointerexception异常。
为了避免这种异常的发生,我们可以在使用之前先进行null值检查(即判空),或者给变量分配好内存空间并赋予初值。
比如在判断一个string类型的实例s是否等于“a”时,应该写成”a”.equals(s),而不是s.equals(“a”),因为前者能够避免s为空的情况,从而避免nullpointerexception的发生。
同样地,在方法的返回值中,可以将返回类型定义为数组,以避免返回null值的情况。如果需要返回空值,则可以返回一个空数组。
综上所述,避免nullpointerexception的关键是要对变量进行充分的判空和初始化处理,尽量避免使用null值,以及采用安全的编程习惯来规避这种异常。
java程序中nullpointerexception
异常的一些例子。
1. 调用实例方法时出现nullpointerexception
示例代码如下
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());
}
}
是否还在为ide开发工具频繁失效而烦恼,来吧关注以下公众号获取最新激活方式。亲测可用!
【正版授权,激活自己账号】:
【官方授权 正版激活】:
当运行上面的程序时,它会抛出nullpointerexception
异常错误消息。
exception in thread "main" java.lang.nullpointerexception
at temp.main(temp.java:7)
在语句t.foo("hi")
中抛出nullpointerexception
异常; 因为t
在这里为null
。
2. 访问/修改null对象的字段时出现nullpointerexception
示例代码 –
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;
}
}
执行上面示例代码,得到以下结果 –
exception in thread "main" java.lang.nullpointerexception
at temp.main(temp.java:9)
语句int i = t.x
中抛出nullpointerexception
异常; 因为 t
在这里为null
。
3. 在方法参数中传递null时nullpointerexception
示例代码 –
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
参数给调用者。
4. 抛出null时抛出java.lang.nullpointerexception
示例代码
public class temp {
public static void main(string[] args) {
throw null;
}
}
下面是上面程序的异常堆栈跟踪,由于throw null
所以抛出nullpointerexception
异常。
exception in thread "main" java.lang.nullpointerexception
at temp.main(temp.java:5)
5. 获取null数组的长度时抛出java.lang.nullpointerexception
public class temp {
public static void main(string[] args) {
int[] data = null;
int len = data.length;
}
}
执行上面示例代码,得到以下结果 –
exception in thread "main" java.lang.nullpointerexception
at temp.main(temp.java:7)
6. 访问null数组的索引值时出现nullpointerexception
示例代码 –
public class temp {
public static void main(string[] args) {
int[] data = null;
int len = data[2];
}
}
执行上面示例代码,得到以下结果 –
exception in thread "main" java.lang.nullpointerexception
at temp.main(temp.java:7)
7. 在null对象上同步时出现java.lang.nullpointerexception
public class temp {
public static string mutex = null;
public static void main(string[] args) {
synchronized(mutex) {
system.out.println("synchronized block");
}
}
}
synchronized(mutex)
将抛出nullpointerexception
,因为mutex
对象为null
。
8. java.lang.nullpointerexception引发http状态500
有时会将错误页面作为java web应用程序响应发送,错误消息为“http状态500 – 内部服务器错误”,根本原因就是java.lang.nullpointerexception
异常。
下面是一段编辑了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";
}
下图显示了web应用程序响应引发的错误消息。
异常堆栈跟踪
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)
根本原因是语句user.getuserid().tolowercase()
中引发了nullpointerexception
,因为user.getuserid()
返回null
。
检测nullpointerexception
非常简单,只需查看异常跟踪,它将显示异常的类名和行号。然后查看代码并查看可能为null
。只要看一下上面的所有例子,从堆栈跟踪中可以清楚地看出是什么导致了null
指针异常。
如何修复java.lang.nullpointerexception异常
java.lang.nullpointerexception
是一个未经检查的异常,因此不必捕获它。通常可以使用空检查和预防性编码技术来防止空指针异常。请看下面的代码示例,演示如何避免java.lang.nullpointerexception
异常。
示例1
if(mutex ==null) mutex =""; //preventive coding
synchronized(mutex) {
system.out.println("synchronized block");
}
示例2
//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());
}
1 . 考虑下面的代码示例。
public void foo(string s) {
if(s.equals("test")) {
system.out.println("test");
}
}
2 . 现在,如果将null
作为s
参数的值传递,则会发生nullpointerexception
异常。可以如下编写相同的方法以避免nullpointerexception
。
public void foo(string s) {
if ("test".equals(s)) {
system.out.println("test");
}
}
3 . 需要为参数添加null
检查,并在需要时抛出illegalargumentexception
异常。
public int getarraylength(object[] array) {
if(array == null) throw new illegalargumentexception("array is null");
return array.length;
}
4 . 使用三元运算符,如下面的示例代码所示。
string msg = (str == null) ? "" : str.substring(0, str.length()-1);
5 . 使用string.valueof()
而不是tostring()
方法。例如,检查printstream println()
方法代码定义如下。
public void println(object x) {
string s = string.valueof(x);
synchronized (this) {
print(s);
newline();
}
}
6 . 下面显示了使用valueof()
方法而非tostring()
的示例。
object mutex = null;
//prints null
system.out.println(string.valueof(mutex));
//will throw java.lang.nullpointerexception
system.out.println(mutex.tostring());
7 . 写入方法尽可能返回空对象而不是null
,例如空列表,空字符串等。
8 . 应该使用在集合类中定义了一些用来避免nullpointerexception
的方法。例如
contains(),containskey()和containsvalue()。
这是关于java中的nullpointerexception
异常的所有情况。希望它能帮助您编写更好的代码,以尽可能避免java.lang.nullpointerexception
异常。
文章由思创斯整理,转载请注明出处:https://ispacesoft.com/141649.html