SObjectException No More. Intentional Change?

I found a pretty surprising change in platform behavior today.


Minimum Viable Reproduction (MVR)

Script

It’s simple to reproduce. Just run this script in Execute Anonymous:

Account a = [SELECT Id FROM Account LIMIT 1];
a.Phone = '1111111111';
system.debug(a.Name);

Expected Behavior

There should be an uncaught exception.

Execute Anonymous Error
Line: 3, Column: 1
System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: Account.Name

Observed Behavior

There is no exception, but the field is seen as null.

[3]|DEBUG|null


Question

Is this an intentional change, or a bug that was introduced as part of Spring 17? Or was it introduced in an earlier release and I just didn’t notice?

Clarification

I considered it obvious based on the M in Minimum Viable Reproduction, but I should be explicit that I already discovered the behavior is still as expected if you don’t set any fields. It seems that setting a field is what causes the change in behavior.

Account a = [SELECT Id FROM Account LIMIT 1];
system.debug(a.Name); // still throws

Answer

Support has agreed that this behavior is a bug and informed me there is an ETA to fix it (though they did not share that timeline). They did not share if a Known Issue was created, but it looks like this issue was reported as early as last year:

System.SObjectException is not thrown while executing piece of apex code without querying that field

Summary
System.SObjectException is not thrown while executing below apex code without querying that field after put statement.

Repro
– Issue is replicable in any org by executing the below piece of code.

Go to dev console or workbench:

  1. Execute the following anonymous apex: [WORKING AS EXPECTED]

    sobject so = [SELECT Id FROM Contact LIMIT 1]; 
    System.debug(so.get('Name')); 
    

Result: System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: Contact.Name

  1. Execute this similar anonymous apex: [NOT WORKING AS EXPECTED]

    sobject so = [SELECT Id FROM Contact LIMIT 1]; 
    so.put('Description', 'This is a description'); 
    System.debug(so.get('Name')); 
    

Result: No exception is being thrown. The debug statement outputs null.

Workaround
– Please make sure to query that the required fields in your SOQL query.

Attribution
Source : Link , Question Author : Adrian Larson , Answer Author : Adrian Larson

Leave a Comment