java.lang.NullPointerException的可能原因及处理

java.lang.NullPointerException的可能原因及处理

java.lang.NullPointerException具体意思是空指针异常,最常见的问题就是没有初始化。

  1. 字符串等数据类型没有初始化
  2. 类实例(对象)有用具体的类初始化
  3. 没有判断是否为空

Eg:

源码:

 public static BookInformation[] ImFromClassification(String a){
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
int x = 0;
conn = LinkMysql.getDBconnection();
if(conn == null){System.out.println("conn");}
String sql="select * from bookinformation where classification=?";
ps = conn.prepareStatement(sql);
ps.setString(1, a);
rs = ps.executeQuery();
rs.beforeFirst();
while(rs.next()){
++x;
}
System.out.println(x);
BookInformation[] a1 = new BookInformation[x];
rs.first();
for(int i = 0; i < x; i++){
//a1[i] = new BookInformation();
a1[i].setName(rs.getString("name"));
a1[i].setAuthor(rs.getString("author"));
a1[i].setClassification(rs.getString("classification"));
a1[i].setAmount(rs.getInt("amount"));
a1[i].setPrice(rs.getInt("price"));
a1[i].setSalvesVolum(rs.getInt("sales_volum"));
rs.next();
}
return a1; } catch (SQLException e) {
System.out.println("xxx");
return null;
}
finally{LinkMysql.closeDB(conn, ps, rs);} }

报错:

root cause

java.lang.NullPointerException
Dao.BookInfor.ImFromClassification(BookInfor.java:31)
org.apache.jsp.front.home_jsp._jspService(home_jsp.java:120)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:439)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

分析:

数组定义(BookInformation[] a1 = new BookInformation[5])之后,没有对每个数组元素初始化。

更改:

 public static BookInformation[] ImFromClassification(String a){
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
int x = 0;
conn = LinkMysql.getDBconnection();
if(conn == null){System.out.println("conn");}
String sql="select * from bookinformation where classification=?";
ps = conn.prepareStatement(sql);
ps.setString(1, a);
rs = ps.executeQuery();
rs.beforeFirst();
while(rs.next()){
++x;
}
System.out.println(x);
BookInformation[] a1 = new BookInformation[x];
rs.first();
for(int i = 0; i < x; i++){
a1[i] = new BookInformation();
a1[i].setName(rs.getString("name"));
a1[i].setAuthor(rs.getString("author"));
a1[i].setClassification(rs.getString("classification"));
a1[i].setAmount(rs.getInt("amount"));
a1[i].setPrice(rs.getInt("price"));
a1[i].setSalvesVolum(rs.getInt("sales_volum"));
rs.next();
}
return a1; } catch (SQLException e) {
System.out.println("xxx");
return null;
}
finally{LinkMysql.closeDB(conn, ps, rs);} }
上一篇:java 空指针异常(java.lang.NullPointerException)


下一篇:CrashHandler: java.lang.NullPointerException