Introduction to Exception Handling in Salesforce Apex

Introduction to Exception Handling in Salesforce Apex

Whenever you use a controller extension, extending a standard object, you can use the getRecord() to get the reference to the record. Most of us think that as soon as we call the getRecord() method, then the entire record is loaded into the contact variable. However, if you have an object with 1000 fields, and you only need to use 4 or 5 in your Visualforce pages, then does that make sense to load all the Fields on that Object? Think about it



public class RecordContactExt {
    private Contact contact;
    public RecordContactExt(ApexPages.StandardController sController) { = (Contact)sController.getRecord();

    public String getCustomMessage() {
        return 'Aquaman, Wayne told the ' + contact.FirstName + ', “I believe that an enemy is coming from far away. ';


<apex:page standardController="Contact" extensions="RecordContactExt">

Save it and Click on Preview. You will get something like this:


Now refer the Id of the Contact whose data you want to display by appending?ID=0037F000001xxxx to the Header.


As soon as you will HIt Enter, you will get the following Error:


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

Possible Solutions:

<apex:outputText value="{!contact.FirstName}"/>

If you don't want to display the contact name twice!!

<apex:outputText value="{!contact.FirstName}" rendered="false" />

or Use <apex:variable> instead, such as:

<apex:variable value="{!contact.FirstName}" var="contactFName" />


When you load this Visualforce page, the standard controller will scan through your Visualforce page and knows that you need this field, and when making the getRecord() method call, it automatically and implicitly adds this FirstName field into the SOQL.

Always remember, if you want to use any field in your extension via the getRecord() method, you need to let it be known by making sure that the field exists in your Visualforce page!

Another alternative is to write your own SOQL in your Apex class, but why make an extra SOQL call when you can avoid it?


"Great Leaders Make People See The Best Parts Of Themselves".


Comments are closed.

Popular Salesforce Blogs