ArrayIndexOutOfBoundsException
Codeaft.java
class Codeaft
{
    public static void main(String args[])
    {
        String[] s={"Mango","Pineaple","Grapes","Banana","Apple","Strawberry"};
        System.out.println("Array Length: "+s.length);
        System.out.println("First Element: "+s[0]);
        System.out.println("Last Element: "+s[5]);        
        System.out.println(s[6]);
    }
}
Output
codeaft@codeaft:~$ javac Codeaft.java
codeaft@codeaft:~$ java Codeaft Array Length: 6 First Element: Mango Last Element: Strawberry Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 6 at Codeaft.main(Codeaft.java:10) codeaft@codeaft:~$
Java program to handle the ArrayIndexOutOfBoundsException
Codeaft.java
class Codeaft
{
    public static void main(String args[])
    {
        String[] s={"Mango","Pineaple","Grapes","Banana","Apple","Strawberry"};
        System.out.println("Array Length: "+s.length);
        System.out.println("First Element: "+s[0]);
        System.out.println("Last Element: "+s[5]);
        try
        {
            System.out.println(s[6]);
        }
        catch(ArrayIndexOutOfBoundsException e)
        {
            System.out.println("Requested element not found");
        }
    }
}
Output
codeaft@codeaft:~$ javac Codeaft.java
codeaft@codeaft:~$ java Codeaft Array Length: 6 First Element: Mango Last Element: Strawberry Requested element not found codeaft@codeaft:~$
Java program to display exception throwable details using the printStackTrace() method
Codeaft.java
class Codeaft
{
    public static void main(String args[])
    {
        String[] s={"Mango","Pineaple","Grapes","Banana","Apple","Strawberry"};
        System.out.println("Array Length: "+s.length);
        System.out.println("First Element: "+s[0]);
        System.out.println("Last Element: "+s[5]);
        try
        {
            System.out.println(s[6]);
        }
        catch(ArrayIndexOutOfBoundsException e)
        {
            System.out.println("Requested element not found");
            e.printStackTrace(); 
            System.out.println(e);
        }
    }
}
Output
codeaft@codeaft:~$ javac Codeaft.java
codeaft@codeaft:~$ java Codeaft Array Length: 6 First Element: Mango Last Element: Strawberry Requested element not found java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 6 at Codeaft.main(Codeaft.java:12) java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 6 codeaft@codeaft:~$
Comments and Reactions