How to Solve the List index out of bounds: 0 issue

  • 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

    Thanks

    Kittu: Please update your original question instead of this duplicate.

  • In all probability it is occuring where youre trying to access the value by index and your soql query is unable to find any matching records.

    The size() method on a null would throw a null pointer exception rather than an index out of bounds so I'm guessing the code in braces tries to access u[0]

    You can add a not null check to each of your if statements or alternatively use the native isEmpty method, eg

    If(u!=null && u.size() > 0)
    

    Or alternatively

    If(!u.isEmpty())
    

    hi techtrekker thanks for your response .. but i used what you said that is not working still i am facing same problem...

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM

Tags used