• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Handling NullPointerException?

 
Tanzy Akhtar
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Whether code should handle the NPE(NullPointerException)?
As per basic rules, code should not take care of NPE.
Please let me know the thoughts and advices accordingly.

Thanks,
Tanzy.
 
Campbell Ritchie
Sheriff
Pie
Posts: 50277
80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As a general rule, no, don't handle NPEs (NullPointerException). Let them propagate and work out what caused the Exception. Handling an NPE will simply allow the null to stay around and cause more trouble later on.
 
Dev Dutta
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There isn't much you can do while handling the NPE. You just capture the NPE and using JVM stack trace, you modify your code to get rid of NPE.
 
Tanzy Akhtar
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Campbell and Dev for the sincire reoly.
Well, the idea behind asking this was, if code does not handle NPE externally then
without analyzing the code we can never say which object is actually null.
I got this during my project code, so i asked for the same.

Thanks,
Tanzy.
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if code does not handle NPE externally then without analyzing the code we can never say which object is actually null.

If it's not handled, your program will crash, and the full stack trace, with line numbers (if debug information is included), should be output. You can then tell where the NPE happened, and generally find which instance was null.
 
Tanzy Akhtar
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Christophe for the suggestion.
 
Muhammad Khojaye
Ranch Hand
Posts: 449
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
tanzy akhtar wrote:if code does not handle NPE externally then without analyzing the code we can never say which object is actually null.

There are tools like FindBugs (and others) that can easily generate warnings when a null pointer is dereferenced in the code.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic