Ovoxo Ovoxo - 2 years ago 66
Java Question

Handle Nullpointerexception after SQL query has no result

I've got a MVC based Java application with three models: Room, Student and StudentRoom.

contains an object of Room and Student.

Now I've got the problem that if my SQL query returns no result and I check the value of student's name like this

if(studentRoom.student.name != null) {

I'll get a Nullpointerexception and I don't know how to handle it.

Should I set
Student.name = "";
since my query has no result?

Answer Source
if(studentRoom != null && studentRoom.student != null && studentRoom.student.name != null){
  //.. Access student

Above solution looks a bit weird. you should better use getter/setter methods instead of directly accessing the objects.

Apart from that you can define methods like isStudentAvailable() in studentRoom to check whether it has Student in it or not.

Should I set Student.name = ""; since my query has no result ?

It completely depends on your use case. But I must say better to keep it null as it will raise the exception instead of passing the null check validations.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download