Java 空指针和异常

到底什么是空指针?如何从根源上避免空指针?

  •   空:内存地址   
  •   指针:引用 
  •   异常:运行时

出现空指针的几种情况: 

第一种情况:调用了空对象的实例方法

User user = null;

user.print();

第二种情况:访问了空对象的属性

User user = null;

System.out.print(user.name);

第三种情况:当数组是一个空对象的时候,取它的长度

User user = new User();

System.out.print(user.address.length);

第四种情况:null 当作Throwable的值

CustomException exception = null;

throw exception;

第五种情况:方法的返回值为null,调用方法直接去使用

User user = new User();

System.out.print(user.readBook());

如何避免出现空指针异常?

  • 使用之前一定要初始化,或者检查是否初始化
  • 尽量避免在函数中返回NULL,或给出详细的注释(良好的编程习惯)
  • 外部传值,除非有明确的说明(非NULL),否则,一定要即使判断
  • ......

实际案例:

1)直接打印的时候

System.out.print(request.getParameter("username"));

改为:

if(request.getParameter("username")){ 

  System.out.print(request.getParameter("username"));

}else{

  throw exception;

}

2)给对象重新赋值的时候又调用

User user = new User();

Tools tool = new Tools();

user = tool.getUser();

user.print();

改为:

user = tool.getUser() == null ? new User() : tool.getUser();

原文地址:https://www.cnblogs.com/yhc-love-cl/p/13951537.html