5

I am getting a System.NullPointerException: Attempt to de-reference a null object in the last line (the one with the return) of the following code.

  ...
  AggregateResult result = getResult(...);
  Decimal value = (Decimal) result.get(fieldName);
  return (value == null) ? 0 : value;
}

This really sounds strange to me as I added this line to prevent Nullreference errors. As this code is - let me called it - hard to debug I need to analyse this in my head and not in the IDE ;)

I can only think of 3 error sources that would throw other errors:

  1. AggregateResult result is null -> Would throw an error in the line above.
  2. fieldName does not exist on on result -> Would also throw an error in the line above
  3. Value can not be casted into a Decimal -> Would show different Exception

Might this be be a side effect of code in the return statement?!

4
  • 3
    I suspect it may be an order of operations thing in the return statement. What if you assign the ternary operator to a temp variable and return that instead?
    – Mike Chale
    Jul 8, 2013 at 15:06
  • What is the type of the field you're getting when the error occurs?
    – Matt K
    Jul 8, 2013 at 16:18
  • The same as in the 99% non failing jobs - Decimal. Jul 8, 2013 at 17:25
  • 2
    I've seen the exception line numbers be off by one line previously. If this is the case here I'd suspect the result is causing the null exception. Try setting the Apex code logging to Finest. Jul 9, 2013 at 8:43

2 Answers 2

3

I've seen the exception line numbers be off by one line previously - see Incorrect line reference from NullPointerException.

If this is the case here I'd suspect the result in (Decimal) result.get(fieldName) is causing the null exception and the NullPointerException is incorrectly indicating the following line.

Oddly enough, when I last encountered this, Salesforce support suggested setting the Apex code logging to Finest. Somehow this corrects the line number reference. It's a good head scratcher on how the exception handling is dependant on the logging!

2

Try splitting the ternary into an if-else statement to debug it:

  ...
  AggregateResult result = getResult(...);
  Decimal value = (Decimal) result.get(fieldName);

  system.debug(value);

  if(value == null) { 
    return 0; 
  }
  else { 
    return value; 
  }
}

That would at least give you different line numbers for the error, and it may help you pinpoint why it is occurring. If you find out what it is, you can always change it back.

1
  • "...As this code is - let me called it - hard to debug I need to analyse this in my head and not in the IDE ;)..." Jul 9, 2013 at 7:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .