• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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: 79397
377
  • 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.

 
Without subsidies, chem-ag food costs four times more than organic. Or this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic