文档章节

关于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
苏州
后端工程师
help~~关于java莫明其妙的打印n多java.lang.NullPointerExceptio

我有一个项目,不知为什么莫明其妙的打印n多java.lang.NullPointerException 就象这样 java.lang.NullPointerException java.lang.NullPointerException java.lang.NullPointerException jav......

JavaGG
2010/06/29
120
3
关于groovy的变量与常量运算结果的问题

运行环境:eclipse4.4 groovy 2.3.6 代码如下: class Test{ } 结果是12.2 将会报错 Caught: java.lang.NullPointerException: Cannot invoke method multiply() on null object java.lang.N......

奔跑的野马
2014/08/31
798
1
好的搜索技巧能够造就好的程序员

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

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

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

Triangle23
2014/12/02
0
1
jsp+javabean数据库操作报错

关于jsp中使用javabean老报空指针异常javbean代码:public class connectsql { public static Statement getStatement(){Connection conn=null;Statement stmt=null;String url="jdbc:sqlser......

淡淡爱ing
2016/04/23
99
1

没有更多内容

加载失败,请刷新页面

加载更多

CentOS7防火墙firewalld操作

firewalld Linux上新用的防火墙软件,跟iptables差不多的工具。 firewall-cmd 是 firewalld 的字符界面管理工具,firewalld是CentOS7的一大特性,最大的好处有两个:支持动态更新,不用重启服...

dingdayu
今天
1
0
关于组件化的最初步

一个工程可能会有多个版本,有国际版、国内版、还有针对各种不同的渠道化的打包版本、这个属于我们日常经常见到的打包差异化版本需求。 而对于工程的开发,比如以前的公司,分成了有三大块业...

DannyCoder
今天
2
0
Spring的Resttemplate发送带header的post请求

private HttpHeaders getJsonHeader() { HttpHeaders headers = new HttpHeaders(); MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8"); ......

qiang123
昨天
3
0
Spring Cloud Gateway 之 Only one connection receive subscriber allowed

都说Spring Cloud Gateway好,我也来试试,可是配置了总是报下面这个错误: java.lang.IllegalStateException: Only one connection receive subscriber allowed. 困扰了我几天的问题,原来...

ThinkGem
昨天
31
0
学习设计模式——观察者模式

1. 认识观察者模式 1. 定义:定义对象之间一种一对多的依赖关系,当一个对象状态发生变化时,依赖该对象的其他对象都会得到通知并进行相应的变化。 2. 组织结构: Subject:目标对象类,会被...

江左煤郎
昨天
4
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部