aspose file tools*
The moose likes Beginning Java and the fly likes Handling NullPointerException? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Handling NullPointerException?" Watch "Handling NullPointerException?" New topic
Author

Handling NullPointerException?

Tanzy Akhtar
Ranch Hand

Joined: Jul 19, 2009
Posts: 110
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.


Roll with punchers, there is always tomorrow.
Techie Blog -- http://jtanzy.blogspot.com/
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39815
    
  28
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

Joined: Dec 24, 2009
Posts: 1
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

Joined: Jul 19, 2009
Posts: 110
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

Joined: Nov 24, 2005
Posts: 14688
    
  16

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.


[My Blog]
All roads lead to JavaRanch
Tanzy Akhtar
Ranch Hand

Joined: Jul 19, 2009
Posts: 110
Thanks Christophe for the suggestion.
Muhammad Khojaye
Ranch Hand

Joined: Apr 12, 2009
Posts: 449

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.


http://muhammadkhojaye.blogspot.com/
 
Consider Paul's rocket mass heater.
 
subject: Handling NullPointerException?