java.lang.nullpointerexception出现的几种原因及金沙1005的解决方案 -金沙1005

java.lang.nullpointerexception出现的几种原因及金沙1005的解决方案主要介绍了java.lang.nullpointerexception出现的几种原因及金沙1005的解决方案,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下java.lang.nullpointerexception出现的几种原因:1、字符串变量未初始化2、接口类型的对象没有用具体的类初始化3、当一个对象的值为空时,你没有判断为空的情况。

java.lang.nullpointerexception是java编程中最常见的异常之一。任何使用java的人都有在java程序以及java web应用程序中看到java.lang.nullpointerexception异常。

java.lang.nullpointerexception出现的几种原因及金沙1005的解决方案

nullpointerexception是一个运行时异常,因此不需要在程序中捕获它。

当尝试在null对象上执行某些操作时,会在应用程序中引发nullpointerexception异常。以下是在java程序中发生nullpointerexception异常的一些常见原因 –

  • 在对象实例上调用方法,但在运行时对象为null
  • 访问在运行时为null的对象实例的变量。
  • 在程序中抛出null
  • 访问索引或修改索引的数组为null
  • 检查在运行时为null的数组的长度。
该文主要介绍了 java.lang.nullpointerexception 出现的几种原因及金沙1005的解决方案 , 本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

在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());
    }
}
java.lang.nullpointerexception出现的几种原因及金沙1005的解决方案

为防止网络爬虫,请关注公众号回复”口令”

激活idea 激活clion
datagrip dataspell
dotcover dotmemory
dottrace goland
phpstorm pycharm
resharper reshac
rider rubymine
webstorm 全家桶

当运行上面的程序时,它会抛出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应用程序响应引发的错误消息。

java.lang.nullpointerexception出现的几种原因及金沙1005的解决方案

异常堆栈跟踪


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异常。


 

js555888金沙老品牌的版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由思创斯整理,转载请注明出处:https://ispacesoft.com/141649.html

(0)

相关推荐

  • javascript删除数组元素的7个方法javascript删除数组元素的7个方法在javascript中,除了object之外,array类型(数组)恐怕就是最常用的类型了。与其他语言的数组相比,javascript中的array非常灵活。这种灵活性有利有弊,好处是其富有创造性,可以提供各种灵活的金沙1005的解决方案;坏处是容易脑子不够用,因为事实上,它太灵活了,灵活到无法控制的抓狂。前面调侃了几句,回归正题,这里要总结7个在javascript中删除array元素的方法,分别是利用length属性、delete关键字、pop()栈方法、shift

  • java初始化_int数组初始化静态初始化是直接创建加赋值 动态初始化,具有默认值//不赋值直接打印会打印出数组类型的默认值 int,byte,short,long=0 double,float=0.0 char=u0000 boolean=false string=null(引用类型) 数组下标越界异常 数组长度,arr.le …

  • java logout_java core.logout方法代码示例importcom.mendix.core.core;//导入方法依赖的package包/类privatevoidlogin(imxruntimerequestreq,imxruntimeresponseresp)throwsexception{stringcontinuation=req.getparameter(continuation_param);detectco…

    2022年12月22日
  • java-xml[亲测有效]java-xml

  • java中父类引用指向子类对象_子类构造方法调用父类构造方法原文地址http://www.cnblogs.com/111testing/p/6880831.htmljava多态的三个必要条件:1、继承2、子类重写父类方法3、父类引用指向子类对象然后看一个例子输出结果为:给出结论:father c = new child()  在c的眼里只能看到child

    2022年12月30日
  • java insert方法_java stringbuilder insert()方法「终于解决」javastringbuilderinsert()方法java.lang.stringbuilder.insert(intdstoffset,charsequences)方法插入指定的charsequence到这个序列。charsequence参数的字符插入的顺序,在这个顺序的指定位置,向上移动原来的字符的位置和由参数s的长度增加该序列的长度。1语法publicstringbuil…

  • java datainputstream_java datainputstream readunsignedbyte()方法javadatainputstreamreadunsignedbyte()方法java.io.datainputstream.readunsignedbyte()用于读取一个输入字节,将其零扩展以键入int类型,然后返回结果,因此其范围为0到255。1语法publicfinalintreadunsignedbyte()2参数无3返回值此方法返回无符号的8位值。4示例packag…

  • java链表listnode导包_java实现listnode链表反转-三种方法链表是一种常见的数据结构,由一个个节点通过指针连接而成。每个链表节点由数据域和指针域组成,其中数据域用来存储数据data,指针域用来存储指向下一节点的指针next,即指向下一节点的地址。[code]publicclasslistnode{objectdata;//数据域listnodenext;//指针域publiclistnode(objectdata){this.data=d…

发表回复

您的电子邮箱地址不会被公开。

联系金沙1005

关注“java架构师必看”公众号

回复4,添加站长微信。

附言:ispacesoft.com网而来。

关注微信
网站地图