+ Start a Discussion
Monishan MMonishan M 

List index out of bound exception for the Apex code

Hi All,

Below is my piece of code.
String val[];
 String response = ' false ; My name is XXX' ,
Map<Ids, String > miverr = new Map<Ids , String >() ;


val =  response.split(';');

if (val[0] == 'true') {
                 {
                    submittedInquiries = Done
                }
               
            else {
                
               thisMI = a00123456rtg4h57;
                miverr.put(thisMI,val[1]);

}

Problem is if the Val[1] becomes null in some cases, exception is being thrown.

Example: List index out of bound except at lin 18 column 81.....

Can you please let me know how to handle this.

Thanks,
Monisha
              
 
SwethaSwetha (Salesforce Developers) 
HI Monisha,
In a scenario like this, the best practice is to check whether there are records in the list before accessing any element from that list.
You need to alter you code to something like below:
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!!

Related/Examples: 
https://sfdctechie.wordpress.com/2018/06/15/system-listexception-list-index-out-of-bounds-explained-with-example/
https://help.salesforce.com/articleView?id=000329067&type=1&mode=1
https://salesforce.stackexchange.com/questions/208280/deployment-error-system-listexception-list-index-out-of-bounds-0

Hope this helps you. Please mark this answer as best so that others facing the same issue will find this information useful. Thank you
Monishan MMonishan M
Hi Sweta,

Thanks for the reply,

But i need to capture both the null as well as notnull records in the list and process it in my logic

For example 
Value has a response and its message I receive for an ID when I submit.
If the response is true i am appending the message of the response in the value as true; message 
If the response is false i am appending the message of the response in the value as false;message

here the value constantly has true ; XXX value or false ; XXX value

But there are some cases where val is just true ;  (i.e - I am not getting any message for the response when I submit ID)

But I need to process both true as well as false records in my code and print message if I get it or else just leave it as blank in my code.

Can you please let me know how this can be done



Thanks