[SalesForce] List index out of bounds: 0

How can I solve the List index out of bounds: 0 issue .

  ID Accid;

  Account[] acc = [Select id,name from account where name ='test']; -->1
  if(acc.size() >0){
     Accid = acc[0].id;
   }else {
    Account[] acc1 =[Select id,name from Account where name = 'test 1'];-->2
    if(acc1.size()>0){
       Accid = acc1[0].id;
     }
   }

  User[] u = [Select id,Name from User Where Accountid=:Accid];-->3 
  if(u.size() >0){ //here throw the error like List index out of bounds: 0
    //some logic here
    //
   }

  ------some code---------
  --- some code-----------
  ---- some code----------

Here i got issue that is 1 query executed then 3 query executed size 0 after iI am not get any error executed next lines that's work fine. but 2 query executed then 3 query executed size 0 now next lines not executed that's throw the error like List index out of bounds: 0

Best Answer

You're referencing the wrong array in the second if statement, see the BAD LINE comment in the code below

ID Accid;

Account[] acc = [Select id,name from account where name ='test']; -->1
if (acc.size() > 0) {
    Accid = acc[0].id;
} else {
    Account[] acc1 =[Select id,name from Account where name = 'test 1'];-->2
    if (acc1.size() > 0) {
        Accid = acc[0].id; // BAD LINE, should be Accid = acc1[0].id
    }
}

User[] u = [Select id,Name from User Where Accountid=:Accid];-->3
Related Topic