+ Start a Discussion

Confusing Null Pointer exception

in my code I have the following statement:



for(Node child : curNode.children){    			
  //do anything	    	



Which is throwing a null pointer exception when curNode.children is null. I would expect, that if curNode.children were null, than it would not execute the for loop.  I can execute a repeat statement in Visualforce using curNode.children as the value and it works fine.  I also have many of these for loops scattered throughout a lot of code and have never had an issue before, but now I find that I need to wrap the code with the following:


if(curNode.children != null){
    //for loop code

 in order to get it to work. 


Is there something I'm just completely overlooking here or is this the expected behavior?  I understand that if curNode were null, than trying to reference a variable inside of it would result in a null pointer, but how is referencing a null variable inside of a non-null object throwing that?


Please forgive me if this is something ridiculous, it's late here :)










Nothing is unusual in the code written by you, neither are you overlooking anything.

Generally we developers when write our first cut of code test it with data which is going to pass - so probably in your initial runs you executed your code with data having child records hence you didnot encounter any error.

It is imperative to handle null in all your code so that it does not throw error when it does not get a resultset or gets a null resultset.

So you should put null handlers as a rule in all your code.

Hope this helps.