Search code examples
javaindexoutofboundsexception

How can I prevent or handle java.lang.ArrayIndexOutOfBoundsException in this code?


I am doing a telephone directory with arrays (I have to use arrays). When I try to pass an entry line that only contains surname and initials (not the number) or just surname, I want to throw an IllegalArgumentException. However, when I tried to test it I get thrown an ArrayIndexOutOfBoundsException instead.

This is some of the addEntry method.

@Override
    public void addEntry(String line) throws IllegalArgumentException{

        int size = entries.length;

        String[] newLine = line.split("\\s+");
        String surname = newLine[0];
        String initials = newLine[1];
        String number = newLine[2];

        if (surname.length()<1 || initials.length()<1 || number.length()<1){
            throw new IllegalArgumentException("Please provide a Surname, Initials and a Number");
        }


        Entry newEntry = new Entry(surname, initials, number);

If i try to pass to the method this entry: arrayDirectory.addEntry("Lara AL");

I get this error message:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2

pointing here: String number = newLine[2];


Solution

  • Before assigning to varirable check the length of array. Like :

    @Override
        public void addEntry(String line) throws IllegalArgumentException{
    
            int size = entries.length;
    
            String[] newLine = line.split("\\s+");
            if(newLine.length < 3)throw new IllegalArgumentException("Please provide a Surname, Initials and a Number");
            String surname = newLine[0];
            String initials = newLine[1];
            String number = newLine[2];
    
            if (surname.length()< 5 || initials.length()< 5 || number.length()< 5){
                throw new IllegalArgumentException("Please provide a Surname, Initials and a Number that is atleast 5 char long");
           //do other validations here like number -  is it a number or maybe has dashes and spaces
    
            }
    
    
            Entry newEntry = new Entry(surname, initials, number);