• Post Reply Bookmark Topic Watch Topic
  • New Topic

NullPointerExcecption Handling - Best Way  RSS feed

 
Vaibhav G Garg
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the best way to handle NullPointerException? Should we check for objects each and everytime when we are invoking any method over it? Or there is some better solution too?
 
Campbell Ritchie
Marshal
Posts: 56584
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no best way to handle a NullPointerException (NPE). Never handle it.
You haven't supplied enough information about how you are getting the null, but for every reference you should think whether null is a permissible value. If it isn't (and it usually isn't), make sure you keep nulls out.
  • Initialise all fields in the constructor.
  • If any nulls get into your methods or constructor as arguments, throw an NPE.
  • If null ever is valid for any reference, you might have to use if (ob != null)... tests.
     
    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
    When you get a NullPointerException, it almost always means that there's a bug in your program. So, what you should do is find the bug and fix it, so that it doesn't happen anymore, instead of trying to write code to deal with the NullPointerException.
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!