function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
k78k78 

Exception not being thrown...

I'm curious if anyone has a good explanation why the exception below is thrown in the first case but not the second case.
Exception Thrown (and rightly so):
sobject so = [SELECT Id FROM Contact LIMIT 1];
System.debug(so.get('Name'));
...but not here:
sobject so = [SELECT Id FROM Contact LIMIT 1];
so.put('Description', 'This is a description');
System.debug(so.get('Name'));

In both cases I would hope that so.get('Name') would throw the exception but I have found this not to be the case.

Exception:
System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: Contact.Name
Best Answer chosen by k78
shashi lad 4shashi lad 4
This is happening because, when we declare sObject with query, it only fetch fields we specify in the query along with Id.  So in your first example, it doesn't have "Name" field fetched. 
However, when you try to use sObject.Put method, in the background, it create a new object, pulls old value of the field which is defined in .put method, and replace the value of field defined in .put method. It also assigns other fields with null value. So now sObject is having all the fields accessbility and avoid exception. You can all other fields from the contact and it shouldn't give you an error.

I hope this explains. Please mark solved if it does.

thanks
shashi

All Answers

David ZhuDavid Zhu
In case two, an exception was thrown on line 2 as 'description' is not a valid field. (not in soql)
k78k78
I have run this in multiple orgs and not got any exception in case 2.  If the Contact object has no visible Description field the example can be easily altered to match whatever Object/Field setup you have.
Chandra Sekhar CH N VChandra Sekhar CH N V
Name is a mandatory field on contact. Include that in your SOQL query and give a try!!!
shashi lad 4shashi lad 4
This is happening because, when we declare sObject with query, it only fetch fields we specify in the query along with Id.  So in your first example, it doesn't have "Name" field fetched. 
However, when you try to use sObject.Put method, in the background, it create a new object, pulls old value of the field which is defined in .put method, and replace the value of field defined in .put method. It also assigns other fields with null value. So now sObject is having all the fields accessbility and avoid exception. You can all other fields from the contact and it shouldn't give you an error.

I hope this explains. Please mark solved if it does.

thanks
shashi
This was selected as the best answer