The System.ListException: List index out of bounds: 0 error occurs in Salesforce Apex when code attempts to access an element at a specific index in a List, but that index does not exist. The most common cause is a SOQL query that returns zero records — when the list is empty and the code tries to access lstAccount[0], Apex throws this error because there is no element at index 0. This article explains why this error occurs and how to prevent it.
Before referencing the 0th index of a list, always check whether the list contains records. The following Apex example shows how to guard against this error using a size check. The code only processes lstAccount[0] if the list contains at least one record:
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!!
000385743

We use three kinds of cookies on our websites: required, functional, and advertising. You can choose whether functional and advertising cookies apply. Click on the different cookie categories to find out more about each category and to change the default settings.
Privacy Statement
Required cookies are necessary for basic website functionality. Some examples include: session cookies needed to transmit the website, authentication cookies, and security cookies.
Functional cookies enhance functions, performance, and services on the website. Some examples include: cookies used to analyze site traffic, cookies used for market research, and cookies used to display advertising that is not directed to a particular individual.
Advertising cookies track activity across websites in order to understand a viewer’s interests, and direct them specific marketing. Some examples include: cookies used for remarketing, or interest-based advertising.