文档章节

关于NullPointerException

-_-struggle
 -_-struggle
发布于 2016/08/10 23:02
字数 815
阅读 2
收藏 0
点赞 0
评论 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
博文 140
码字总数 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 ⋅ 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 ⋅ 1

Java自定义Exception

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

Triangle23 ⋅ 2014/12/02 ⋅ 1

好的搜索技巧能够造就好的程序员

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

涩郎 ⋅ 2017/03/13 ⋅ 0

基于struts1.框架的异常处理方案

首先感谢“郡主”对我的支持,她帮忙完善了跳转地址重定向问题。 1. 目标——什么异常需要我们处理 通常来说,在业务流程中已经将大部分异常进行处理,因为大部分异常是继承java.lang.Excep...

STG0825 ⋅ 2013/09/06 ⋅ 0

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 ⋅ 1

strtus2.1.6+spring2.5.5+hibernate3框架

使用Struts2.1.6+Spring2.5.5+Hibernate3搭建一个开发平台,Web服务器使用JBoss5.0,在搭建过程中遇到一些问题,再次记录以备后来者需要。 1、关于Hibernate版本问题 查看hibernate网站,目前...

晨曦之光 ⋅ 2012/03/09 ⋅ 0

Android学习之BMI1.3

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

pzsoftchen ⋅ 2012/07/30 ⋅ 0

strtus2.1.6+spring2.5.5+hibernate3框架

近几日,使用Struts2.1.6+Spring2.5.5+Hibernate3搭建一个开发平台,Web服务器使用JBoss5.0,在搭建过程中遇到一些问题,再次记录以备后来者需要。 1、关于Hibernate版本问题 查看hibernate...

晨曦之光 ⋅ 2012/03/09 ⋅ 0

Apache PDFBox 1.4.0 发布

PDFBox 是一个用来操作 PDF 文档的 Java 类库。 PDFBox 1.4.0 是 1.x 系列的功能改进版本,包含很多关于文本提取、AES加密和异常PDF文档处理的改进和bug修复。 详情如下: New Features [PD...

红薯 ⋅ 2010/12/21 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

Hive函数

1.函数explode (一转多) create table hive_wc(sentence string); load data local inpath '/home/hadoop/data/hive-wc.txt' into table hive_wc; 结果: hive > select * from hive_wc; ......

GordonNemo ⋅ 27分钟前 ⋅ 0

PE格式第三讲扩展,VA,RVA,FA的概念

作者:IBinary 出处:http://www.cnblogs.com/iBinary/ 版权所有,欢迎保留原文链接进行转载:) 一丶VA概念 VA (virtual Address) 虚拟地址的意思 ,比如随便打开一个PE,找下它的虚拟地址 这边...

simpower ⋅ 45分钟前 ⋅ 0

使用Java connector消费ABAP系统的函数

Java Connector(JCO)环境的搭建:Step by step to download and configure JCO in your laptop 我的ABAP系统有个函数名叫ZDIS_GET_UPSELL_MATERIALS,输入一个customer ID和product ID,会输......

JerryWang_SAP ⋅ 50分钟前 ⋅ 0

IDEA提示编码速度

焦点移动 将焦点冲代码编辑窗口移动到菜单栏:Alt+菜单栏带下划线字母 将焦点从工具窗口移动到代码编辑窗口 Esc或Shift+Esc 将焦点从代码编辑移动到最近使用的工具窗口 F12 模板提示 Ctrl+J...

bithup ⋅ 今天 ⋅ 0

180623-SpringBoot之logback配置文件

SpringBoot配置logback 项目的日志配置属于比较常见的case了,之前接触和使用的都是Spring结合xml的方式,引入几个依赖,然后写个 logback.xml 配置文件即可,那么在SpringBoot中可以怎么做?...

小灰灰Blog ⋅ 今天 ⋅ 0

冒泡排序

原理:比较两个相邻的元素,将值大的元素交换至右端。 思路:依次比较相邻的两个数,将小数放在前面,大数放在后面。即在第一趟:首先比较第1个和第2个数,将小数放前,大数放后。然后比较第...

人觉非常君 ⋅ 今天 ⋅ 0

Vagrant setup

安装软件 brew cask install virtualboxbrew cask install vagrant 创建project mkdir -p mst/vmcd mst/vmvagrant init hashicorp/precise64vagrant up hashicorp/precise64是一个box......

遥借东风 ⋅ 今天 ⋅ 0

python3.6 安装pyhook_3

我的是在win下的,忙了半天老是安装不了, pip install 也不行。 那么可以看出自己的版本是32bit 一脸懵逼 没办法 只好下载32版本的来安装 我一直以为 是 对应32 位的 。 下面是 小例子 http...

之渊 ⋅ 今天 ⋅ 0

004、location正则表达式

1、location的作用 location指令的作用是根据用户请求的URI来执行不同的应用,也就是根据用户请求的网站URL进行匹配,匹配成功即进行相关的操作。 2、location的语法 = 开头表示精确匹配 ^~...

北岩 ⋅ 今天 ⋅ 0

CentOS7 静默安装 Oracle 12c

环境 CentOS7.5 最小安装 数据库软件 linuxx64_12201_database.zip 操作系统配置 关闭 SELinux sed -i '/^SELINUX=/cSELINUX=disabled' /etc/selinux/config 关闭防火墙 systemctl disable ......

Colben ⋅ 今天 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部