• Post Reply Bookmark Topic Watch Topic
  • New Topic

Prevent Null Pointer Exception  RSS feed

 
sudha swami
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
How to prevent Null Pointer Exception in java? What is the good practice?
regards
sudha
 
Bill Shirley
Ranch Hand
Posts: 457
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
don't dereference a null pointer.

your compiler, by default, should warn you of obvious cases,

you should be familiar with APIs,
if they can return a null value, you shouldn't assume it didn't,
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
According to this, you should get a dog.

NullPointerExceptions are usually easy to fix. When one happens, you get a stack trace that tells you exactly in which line of your source code it happened. Go to that line and see what was null there that wasn't supposed to be.

It's good practice to add error checking code to your program at strategic places; not only for checking if that something isn't null when it's not supposed to be, but more in general to check if a method doesn't get passed nonsense values.
 
Niki Nono
Ranch Hand
Posts: 256
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How about

Object1 obj = methodToGetInstance();
if(obj == null) {
//Oops
}
else {
//hallelujah
}
 
Campbell Ritchie
Marshal
Posts: 56545
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Niki Nono:
How about
if(obj == null) {
}
else {
}
That will work nicely for instances (eg closing a Reader, nodes in a Tree) where a null can actually be expected; for other instances where a NPE (=NullPointerException) represents a programming error, all you achieve is hiding the error from yourself.

 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!