Being a Salesforce developer we have often came across this “System.ListException: List index out of bounds ” error . This specific list index out of bounds error in salesforce is a key lesson in Apex troubleshooting and highlights one of the most crucial Apex best practices: never assume a SOQL query will always return data.
Lets breaks down the root cause, shows you why this error coms up , how to reproduce the mistake, provides the solution and resolution.
What Causes the “System.ListException: List index out of bounds” Error?
In Apex, Lists are zero-indexed, meaning the first element lives at index [0].
The error occurs because Apex attempts to retrieve a list element at an index that either does not exist or empty .
Specifically, the index of the first item in any list is 0. If you execute a SOQL query that returns zero records (a SOQL empty result), the resulting list is instantiated but has a size of zero. When your code immediately tries to access myList[0], the system finds that the list is empty, and therefore, the index 0 is out of bounds (or invalid), throwing the list index out of bounds 0 error in salesforce as below:
System.ListException: List index out of bounds: 0
Common Trouble Spots Where this error comes up
| Scenario | Description |
|---|---|
| Non-Existent Record Lookups | A trigger queries a record using a deleted, invalid, or simply non-existent ID. |
| No Matching Filter Criteria | The WHERE clause in your query is too restrictive, resulting in an empty set. |
| USING LIMIT 1 | Developers incorrectly assume LIMIT 1 guarantees a result. It only guarantees at most one result. If zero records match, the list is empty! |
A small demo for : Reproducing and Fixing the Error
You can easily replicate this issue in the Anonymous Apex window of the Developer Console.
The Problematic (Buggy) Code
This code assumes an account with the non-existent name will be returned, causing an error on the final line:
String nonExistentName = 'SalesforceHours__TestAccount_NoExist';
List<Account> accounts = [SELECT Id, Name FROM Account WHERE Name = :nonExistentName LIMIT 1];
// Error code : This line assumes accounts[0] exists!
System.debug('Account ID: ' + accounts[0].Id);

Here is the output screen when we ran code in Anonymous Window

The Correct Apex Code
The solution is simple:
Always verify the list size before accessing its elements.
This turns a potential runtime crash into a controlled, predictable outcome.
String nonExistentName = 'SalesforceHours__TestAccount_NoExist';
List<Account> accounts = [SELECT Id, Name FROM Account WHERE Name = :nonExistentName LIMIT 1];
// CHECK: Verify data exists first
if (accounts.size() > 0) {
System.debug('SUCCESS: Account ID Found: ' + accounts[0].Id);
} else {
System.debug('INFO: Query completed successfully, but no Account records were found.');
}

Here is the output screen : Query completed successfully, but no Account records were found.

Resolution: Validate SOQL Results
To guarantee code stability and prevent runtime exceptions, always use one of the following checks before accessing an element: Use either of the one in your apex code.
if (accounts.size() > 0)if (!accounts.isEmpty())
Best Practices: Build Defensive Code
Incorporating list checks should be a first part of your Apex template.
| Focus Area | Incorrect Approach | Correct Approach |
|---|---|---|
| List Access | Account acc = accounts[0]; | if (!accounts.isEmpty()) { Account acc = accounts[0]; } |
| Error Handling | Allow Apex to throw System.ListException. | Handle empty results gracefully in an else block or by exiting the method. |
| SOQL Queries | Assume records exist based on query design. | Always check list contents before attempting to access elements by index. |
Conclusion
By embedding these checks into your standard Apex development process, you ensure your Salesforce applications are robust, user-friendly, and resilient to edge cases where data simply doesn’t exist. Stop assuming, start validating!
Discover more from Trigger Hours
Subscribe to get the latest posts sent to your email.
1 thought on “How to Resolve “System.ListException: List index out of bounds” Error in Salesforce”