• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • paul wheaton
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Liutauras Vilda
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Piet Souris
Bartenders:
  • salvin francis
  • Mikalai Zaikin
  • Himai Minh

Prevent Null Pointer Exception

 
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
How to prevent Null Pointer Exception in java? What is the good practice?
regards
sudha
 
Ranch Hand
Posts: 457
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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,
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 256
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
How about

Object1 obj = methodToGetInstance();
if(obj == null) {
//Oops
}
else {
//hallelujah
}
 
Marshal
Posts: 72672
317
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.

reply
    Bookmark Topic Watch Topic
  • New Topic