NullPointerException是运行时异常,在java编译期间不进行捕获。简单来说,空指针异常就是,java中的引用没有指向实际存在的对象,此时调用对象的方法或属性当然会抛异常。有以下几种常见情况:
常见的代码错误有如下几种:(1)第一种还比较明显,很快能检查出来:
class Point {
public int x;
public int getX() {
return x;
}
}
public class test1 {
//static Point p1 = new Point(); //改成这样就正确
static Point p1;
public static void main(String args[]){
p1.getX(); //NullPointerException
p1.x = 7; //NullPointerException
}
}
此处如果request.getParameter("age")的结果为null,这里就也会产生这种异常。
String age =request.getParameter("age");
if(age.length()==0){
......
}else{
......
}
(3)这里再说一个不太好看出来的错误,先看错误信息:
type Exception report
message
description The server encountered an internal error that prevented it from fulfilling this request.
exception
java.lang.NullPointerException
RegisterServlet.isValidUsername(RegisterServlet.java:57)
RegisterServlet.doPost(RegisterServlet.java:25)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
note The full stack trace of the root cause is available in the Apache Tomcat/8.0.21 logs.
对应的源代码是:
public boolean isValidUsername(String username){
User user = User.getInstance();
Map<String, String> map = user.getUserMap();
if(username != null && !map.get(username).equals("")){ //注意这行
return true;
}else{
return false;
}
}
map.get(username)有可能是个空值,这里拿来equals(""),当然也会报NullPointerException异常。这里其实跟第二种情况很像,知道错误的原因就能很快排除这类错误。当然,最重要的还是,良好的写代码习惯。
出现这种问题的时候,记得捕捉下这个异常,try catch, throw, throws 等等方法都可以!