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
Harry Smith 5Harry Smith 5 

Need urgent help with an error

We are making an order into Salesforce Staging and getting the following error, and the error issue blocking for an order to be submitted:

[[Error extendedErrorDetails='{[0]}'
message='Opportunity: execution of BeforeInsert
caused by: System.ListException: List index out of bounds: 0
Class.Util_CustomMetadata.query: line 71, column 1
Class.Util_CustomMetadata.getSwitch: line 47, column 1
Class.Util_CustomMetadata.isSwitchActive: line 56, column 1
Trigger.Opportunity: line 3, column 1'
Best Answer chosen by Harry Smith 5
Khan AnasKhan Anas (Salesforce Developers) 
Hi Harry,

Greetings to you!

If you then attempt to access an element at row 0, it'll throw an error as that row doesn't exist. It's good practice to check there are records first in order to make sure that the list is not empty before accessing it.

Check if list is empty:

Before referring to the 0th index of list you must perform a check on whether the list is empty or not. Whenever you try to access records from list first check if its empty or not.
List lstAccount = [Select Id, Name from Account Limit 10];
// Before processing the list check if its empty or not
// It will go inside the loop only if the List is having values in it.
if(lstAccount.size() > 0) {
 // Do something with lstAccount[0].Name
// If you try to access lstAccount[0] without empty check then it will obviously throw that error!!

Considerations for empty list:
  • The query returned no rows to the List after execution.
  • You are also using those field(s) in your class or trigger.
  • In this case you will get a System.ListException: List index out of bounds: 0


I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas