文档章节

关于NullPointerException

-_-struggle
 -_-struggle
发布于 2016/08/10 23:02
字数 815
阅读 3
收藏 0

1、When you declare a reference variable (i.e. an object) you are really creating a pointer to an object. Consider the following code where you declare a variable of primitive type int:

int x;
x = 10;

In this example the variable x is an int and Java will initialize it to 0 for you. When you assign it to 10 in the second line your value 10 is written into the memory location pointed to by x.

But, when you try to declare a reference type something different happens. Take the following code:

Integer num;
num = new Integer(10);

The first line declares a variable named num, but, it does not contain a primitive value. Instead it contains a pointer (because the type is Integer which is a reference type). Since you did not say as yet what to point to Java sets it to null, meaning "I am pointing at nothing".

In the second line, the new keyword is used to instantiate (or create) an object of type Integer and the pointer variable num is assigned this object. You can now reference the object using the dereferencing operator . (a dot).

The Exception that you asked about occurs when you declare a variable but did not create an object. If you attempt to dereference num BEFORE creating the object you get a NullPointerException. In the most trivial cases the compiler will catch the problem and let you know that "num may not have been initialized" but sometime you write code that does not directly create the object.

For instance you may have a method as follows:

public void doSomething(SomeObject obj){
   //do something to obj
}

in which case you are not creating the object obj, rather assuming that is was created before the doSomething method was called. Unfortunately it is possible to call the method like this:

doSomething(null);

in which case obj is null. If the method is intended to do something to the passed-in object, it is appropriate to throw the NullPointerException because it's a user error and the user will need that information for debugging purposes.

Alternatively, there may be cases where the purpose of the method is not solely to operate on the passed in object, and therefore a null parameter may be acceptable. In this case, you would need to check for a null parameter and behave differently. You should also explain this in the documentation. For example, doSomething could be written as:

/**@param obj An optional foo for ____. May be null, in which case 
*  the result will be ____. */
public void doSomething(SomeObject obj){
    if(obj != null){
       //do something
    } else {
       //do something else
    }
}

Finally, http://stackoverflow.com/q/3988788/2775450

 

2、"The best way to avoid this type of exception is to always check for null when you did not create the object yourself." If the caller passes null, but null is not a valid argument for the method, then it's correct to throw the exception back at the caller because it's the caller's fault. Silently ignoring invalid input and doing nothing in the method is extremely poor advice because it hides the problem.

 

3、Check if the object equals null before you invoke a method on it or try to access a variable it might have. Some times structuring your code can help avoid null pointer exception. eg when checking an input string with a constant string you should start with the constant string like here: if ("SomeString".equals(inputString)) {} //even if inputString is null no exception is thrown. So there are a bunch of things that you can do to try to be safe.
 

They're exceptions that occur when you try to use a reference that points to no location in memory (null) as though it were referencing an object. Calling a method on a null reference or trying to access a field of a null reference will trigger a NPE. These are the most common, but other ways are listed on the NullPointerException javadoc page.

Probably the quickest example code I could come up with to illustrate a NPE would be:

public class Example
{
    public static void main(String[] args)
    {
        Object obj = null;
        obj.hashCode();
    }
}

On the first line inside main I'm explicitly setting the Object reference obj to null. This means I have a reference, but it isn't pointing to any object. After that, I try to treat the reference as though it points to an object by calling a method on it. This results in a NPE because there is no code to execute in the location that the reference is pointing.

(This is a technicality, but I think it bears mentioning: A reference that points to null isn't the same as a C pointer that points to an invalid memory location. A null pointer is literally not pointing anywhere, which is subtly different than pointing to a location that happens to be invalid.)

 

本文转载自:http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it/218510#

共有 人打赏支持
-_-struggle
粉丝 3
博文 210
码字总数 50914
作品 0
苏州
后端工程师
私信 提问
好的搜索技巧能够造就好的程序员

搜索,是互联网的入口,每个人都离不开搜索,更何况程序员?程序员最离不开的有两样东西,一个是 GitHub ,一个是搜索引擎。离开这两样东西,我相信大部分程序员都不会编程了。所以,一个好的...

涩郎
2017/03/13
0
0
Java自定义Exception

这里总结一下Java的Exception,并实现一个自定义Exception类。 总结: Throwable对象分为两种类型:Error(表示编译时和系统错误);Exception(在Java类库、用户方法以及运行时故障中抛出的异常...

Triangle23
2014/12/02
0
1
Android学习之BMI1.3

上个版本中我们让EditText适应了更实际的输入数值,为了让程序更加像一个真实的应用,现在为程序添加一个菜单列,这个菜单列中包含两项一个是“关于”是用来介绍程序的版本,作者等信息,一个...

pzsoftchen
2012/07/30
0
0
关于map.put()方法,报java.lang.NullPointerException空指针异常

在Java编程中,时不时就会遇到java.lang.NullPointerException的异常,先来看以下代码:[java] view plain copypublic class Test { } 上面这段代码会报异常:Exception in thread "main" ja...

神迹难觅
2017/12/25
0
0
Integer、Long等自动拆箱类型为啥会抛NullPointerException

Integer、Long等自动拆箱类型为啥会抛NullPointerException 戎码一生2017-11-0514 阅读 Java字节码 通常的NullPointerException异常其实是很好判断,一定是有某个对象是null导致的。但是jav...

戎码一生
2017/11/05
0
0

没有更多内容

加载失败,请刷新页面

加载更多

KaliLinux常用服务配置教程DHCP服务工作流程

KaliLinux常用服务配置教程DHCP服务工作流程 DHCP服务工作流程如图1.1所示。 具体的工作流程如下所示: (1)DHCP客户端以广播的方式发出DHCP Discover报文。 (2)所有的DHCP服务器(DHCP ...

大学霸
11分钟前
0
0
Spring Junit单元测试配置

<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.1.2.RELEASE</version></dependency><dependency> <group......

TonyTaotao
15分钟前
0
0
线程安全与非线程安全-个人理解

类的某个方法是线程安全的, 说明这个方法在并发执行中,从开始执行到执行完毕,都是同步的, 比如:之前做的并发数据导出,并发的查询数据库, 但是在写入excel的时候,需要做一个同步,因为...

Java搬砖工程师
17分钟前
1
0
如何提升JavaScript的任务效率?学会后教给你同事

本文由云+社区发表 一、概述 JavaScript 语言采用的是单线程模型,也就是说,所有任务只能在一个线程上完成,一次只能做一件事。前面的任务没做完,后面的任务只能等着。随着电脑计算能力的增...

腾讯云加社区
18分钟前
0
0
Hadoop运行在Kubernetes平台实践

Hadoop与Kubernetes就好像江湖里的两大绝世高手,一个是成名已久的长者,至今仍然名声远扬,一个则是初出茅庐的青涩少年,骨骼惊奇,不走寻常路,一出手便惊诧了整个武林。Hadoop与Kubernete...

微笑向暖wx
18分钟前
0
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部