9

I was trying to retrieve manager.Name going up in hierarchy I also tried to retrieve manager.manager.Name. Field manager.Name was null so I was expecting it to throw an exception. However I didn't got any exception. I tried following code on Developer console:

List<User> userList = [Select manager.Name, manager.Mobile_number__c, manager.manager.Name, manager.manager.Mobile_number__c, manager.Email, manager.manager.Email, manager.manager.manager.Email from User where id = '005900000018D73'];

System.debug('1. :  '+ userList.get(0).manager); //if manager is getting NULL
System.debug('2. :  '+ userList.get(0).manager.manager); // NULL.manager is/should not possible ?! 
System.debug('3. :  '+ userList.get(0).manager.manager.manager);

What I was expecting that it should throw an Exception:

Attempt to de-reference NULL object.

Observation: It runs successfully with no errors.

Can anyone explain why it's happening like this?

2
  • 1
    We have some hierarchy checks within our managed packages and we reference the 5 levels up without using null checks. Spent a day or two testing these scenarios and your results are right. Strange behaviour as opposed to what a developer would expect. Would love to hear an answer to this.
    – TSmith
    Commented Mar 14, 2017 at 13:12
  • @TSmith Yes, I also found it strange. Commented Mar 14, 2017 at 13:13

1 Answer 1

8

Here's the documentation about lookup relantionships.

I'm quoting:

Beginning with API version 13.0, relationship SOQL queries return records, even if the relevant foreign key field has a null value, as with an outer join.

Update

Adding @IllusiveBrian's documentation about accessing relationships.

Quote from this link:

When being read as a value, if c.Account is null, then c.Account.Name evaluates to null, but does not yield a NullPointerException.

2
  • 2
    I hope that one day those will be valid for process builder :)
    – kurunve
    Commented Mar 14, 2017 at 13:29
  • 2
    Also related: documentation (Check the second yellow box). Even without SOQL, sObjects will not throw NullPointerException when read as a field on another object, unless you try to access their Id. Commented Mar 14, 2017 at 14:22

You must log in to answer this question.

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