0

So working through a few Java based web applications, I realized one common thing in pretty much most of the web applications. Most of them tend to run fine until you meet face to face with a Null Pointer Exception. Below is one of the methods that is returning an error:

public Map getWebSiteObjects(String path, LightWeightNode root, Integer versionId, Site site) {


        Map webSiteObjects = new HashMap();

        // refresh site
        site = (Site)getObject(Site.class, site.getId());

        webSiteObjects.put("site", site); ...... /* Dont worry about the rest */

Scenario: This method generates a tree on my application, however, it's giving a null pointer exception at runtime:

2014-10-09 12:00:18,674 ERROR org.springframework.web.servlet.DispatcherServlet - Could not complete request
java.lang.NullPointerException  at com.bsdeurope.xmlcms.service.impl.TreeManagerImpl.getWebSiteObjects(TreeManagerImpl.java:159)

Now I'm quite new with some Java principals(fundamentals) and my idea to solve this was to initialize the 4 variables passed in the method therefore have:

path = null;
root =null;
versionId = null;
site = null;

before any instructions within the getWebSiteObjects method. Now I know this might not be the only solution but my question is:

1) What is good practice in terms of preventing Java Null Pointer Exceptions?
2) If there is a procedure how would you go about doing it?

Usually when working with a lot of classes especially applications with code that is badly written you end up hitting your head against the wall when you get tons of null pointer exceptions left, right and center.

Arty
  • 819
  • 3
  • 13
  • 24
  • 2
    a java developer who does not handle or get NPE is like a fish without water. this is a very broad question and can have multiple solutions and suggestions. I suggest you read through exception handling and especially NPE processing before going ahead – vikeng21 Oct 09 '14 at 11:30

4 Answers4

2

A null check is usually enough.

    // refresh site
    if(site!=null){
        site = (Site)getObject(Site.class, site.getId());
        webSiteObjects.put("site", site); ...... /* Dont worry about the rest */
    }else{
        // Print an error message, or do the error handling here...
    }

Note that, NullPointerException will only come when your expression evaluates to null.someFunction() . In this example, site.getId(). So null check for only site!=null is enough. If you have more object.someFunction() then you may want to do something like

if(obj1!=null && obj2!=null){
    // Safe to call 
    obj1.function();
    obj2.function();
}
Aman Gautam
  • 3,549
  • 2
  • 21
  • 25
  • What about checking if all the params passed in are null. In my method's case all four parameters? Would `if(path || root || site || versionId != null){...}` be a valid sequence? – Arty Oct 09 '14 at 11:36
  • 1
    @Arty: You will see when you try to compile. Try something like `if(path != null || root != null){...}` – Niroshan Oct 09 '14 at 12:00
2

There are two schools of thought on this.

One school, says test for the null and do something to "make good". For example, replace it with something else, ignore it, write a log message, and so on.

The other school is that an unexpected null is a BUG, and the correct thing to do is to allow the NullPointerException to be thrown. Then you allow the NPE to propagate up and (ideally) cause the program to crash ... or better still, fail gracefully after logging the NPE stacktrace in the application's log files.

Then it is up to the programmer to use the information in the stacktrace (and "those little grey cells" to quote a well-known fictional Belgian detective) to figure out where the unexpected null came from, and fix the root cause of the problem. Typically this entails finding the field or array element or whatever that was incorrectly initialized, of the get call that returns a null to indicate (soft) failure, or whatever. This fix may involve testing for null, or it may involve initializing something, or passing something, or correcting some logic, or adding the null test earlier in the program.

IMO, the practice of adding defensive tests for null all over the place is a bad idea. It tends to replace one kind of bug (an NPE) with another kind that is often harder to track down.


So my answers would be:

1) What is good practice in terms of preventing Java Null Pointer Exceptions?

Good practice is to not avoid the NPEs. Instead let them happen, and find / fix what is introducing the spurious null values.

2) If there is a procedure how would you go about doing it?

No there isn't. Certainly there is no procedure that >>I<< would use.

The only thing I would do would be to try to make my code throw the NPE earlier, so that the null doesn't get passed a long way from its original source. (That tends to make it easier to find and fix the root cause of the problem.)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
1

For you Program here is a simple null check:

public Map getWebSiteObjects(String path, LightWeightNode root, Integer versionId, Site site) {


        Map webSiteObjects = new HashMap();
       if(null!=Site){
        // refresh site
        site = (Site)getObject(Site.class, site.getId());

        webSiteObjects.put("site", site); ...... /* Dont worry about the rest */
      }
  //Similarly while using other arguments do similar null check
   (if null!=path){
   /* 
     Your code here...
      */
  }
}

For best practices to avoid NPE check this link: NPE practices

Imran
  • 429
  • 9
  • 23
1

you can put all your business logic of any method in try block

try{
 Map webSiteObjects = new HashMap();
 // refresh site
 site = (Site)getObject(Site.class, site.getId());
 webSiteObjects.put("site", site); ...... /* Dont worry about the rest */
}catch(NullPointerException e){
 // error occured
 e.printStackTrace();
}
Bitan Biswas
  • 51
  • 1
  • 8
  • Bad idea. You have written a stack trace somewhere where it may not be noticed ... and then continued running *as if nothing bad had just happened*! – Stephen C Oct 09 '14 at 11:54
  • it is to let you know where the exception occurred. it has nothing to interrupt the program flow. also it is safe if you don't want your code to be crashed. NPE is runtime exception and should always be taken care. This is my idea of over your two school concept @StephenC – Bitan Biswas Oct 09 '14 at 12:41