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
John Carton 6John Carton 6 

Overcome Null Pointer Exception

String sv1;
String sv2;
String sv3;
String sv4;
for(Opportunity o:[Select CampaignId,Site_Visit_1__c,Site_Visit_2__c,Site_Visit_3__c,Site_Visit_4__c From Opportunity Where CampaignId=:keysForOpp])
 {
     sv1=o.Site_Visit_1__c;
     sv2=o.Site_Visit_2__c;
     sv3=o.Site_Visit_3__c;
     sv4=o.Site_Visit_4__c;

}
If the custom fields are not filled in the records and I try to access them then I am encountering null pointer exception. Is there a way to validate the fields before accessing them? I tried placing those fields inside try-catch block but it  gets clumpsy since I need to write try-catch for every individual field. Is there an alternate way?
 
sfdcMonkey.comsfdcMonkey.com
before access those fields just add null check such as :
String sv1;
String sv2;
String sv3;
String sv4;
for(Opportunity o:[Select CampaignId,Site_Visit_1__c,Site_Visit_2__c,Site_Visit_3__c,Site_Visit_4__c From Opportunity Where CampaignId=:keysForOpp])
 {
     
     sv1=o.Site_Visit_1__c;
     sv2=o.Site_Visit_2__c;
     sv3=o.Site_Visit_3__c;
     sv4=o.Site_Visit_4__c;

}

  if(sv1 != null){
    // do something here..
  }
  
  if(sv2 != null){
    // do something here..
  }
  
  if(sv3 != null){
    // do something here..
  }
  
  if(sv4 != null){
    // do something here..
  }
Thanks, Let us inform if it helps you