文档章节

关于NullPointerException

-_-struggle
 -_-struggle
发布于 2016/08/10 23:02
字数 815
阅读 2
收藏 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

没有更多内容

加载失败,请刷新页面

加载更多

下一页

bat强制启用宏

运行bat文件后,将宏的安全等级设为低,达到启用宏的目的。 REM 这个文件将提供用户快速设置Excel宏的安全等级@ECHO OFFCLS:cmd4REG ADD "HKEY_CURRENT_USER\Software\Mi...

tedzheng
7分钟前
0
0
流,用声明性的方式处理数据集 - 读《Java 8实战》

引入流 Stream API的代码 声明性 更简洁,更易读 可复合 更灵活 可并行 性能更好 流是什么? 它允许以声明方式处理数据集合 遍历数据集的高级迭代器 透明地并行处理 简短定义:从支持数据处理...

yysue
8分钟前
1
0
postman发送json格式的post请求

postman发送json格式的post请求 在地址栏里输入请求url:http://127.0.0.1:8081/getmoney 选择“POST”方式, 在“headers”添加key:Content-Type , value:application/json 点击"body",''ra...

两广总督bogang
15分钟前
0
0
Javascript将html转成pdf,下载(html2canvas 和 jsPDF)

最近碰到个需求,需要把当前页面生成pdf,并下载。弄了几天,自己整理整理,记录下来,我觉得应该会有人需要 :) 项目源码地址:https://github.com/linwalker/render-html-to-pdf html2ca...

孟飞阳
15分钟前
0
0
pureftp源码编译及设定

--- use for RHEL 567 and Ubuntu 1604 1. download pureftpd wget http://download.pureftpd.org/pub/pure-ftpd/releases/pure-ftpd-1.0.47.tar.bz2 2. install gcc #apt-get install -y li......

zzimac
18分钟前
0
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部