文章目录
空指针异常是什么?
空指针异常(java,lang.NullPointException)
可能产生空指针的场景
场景复现
package com.github.ybqdren;
/**
* Wen(Joan) Zhao <withzhaowen@126.com>
* 2021/11/3
*
* <h1>理解什么是空指针</h1>
*/
public class WhatIsNpe {
public static class User{
private String name;
private String[] address;
public void print(){
System.out.println("This is User Class !");
}
public String readBook(){
System.out.println("User Read Imooc Escape !");
return null;
}
}
/**
* <h2>自定义一个运行时异常</h2>
*/
public static class CustomException extends RuntimeException{
}
}
第一种情况:调用了空对象的实例方法
User user = null;
user.print();
控制台抛出异常
Exception in thread "main" java.lang.NullPointerException
at com.github.ybqdren.WhatIsNpe.main(WhatIsNpe.java:29)
堆栈指向了第29行
第二种情况:访问了空对象的属性
User user = null;
System.out.println(user.name);
第三种情况:当数组是一个空对象的时候,取它的长度
此处的User和上面的区别是:此处是有值的。所以访问属性和方法都是可行的,但是数组是没有经过初始化的,是一个空对象因此会报空指针异常
User user = new User();
System.out.println(user.address.length);
第四种情况:null 当作Throwable的值
CustomException exception = null;
throw exception;
第五种情况:方法的返回值为null,调用方直接去使用
User user = new User();
System.out.println(user.readBook().contains("MySQL"));
如何避免引起空指针
● 使用之前一定要初始化,或检查是否初始化
● 尽量避免在函数中返回NULL,或给出详细的注释(良好的编程习惯)
● 外部传值,除非有明确的说明(非NULL),否则,应定要及时判断
● …
参考引用
Java实操避坑指南 课堂笔记