kodingwindow@kw:~$ javac KW.java kodingwindow@kw:~$ java KW
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 KW.main(KW.java:10)
kodingwindow@kw:~$
Java program to handle the ArrayIndexOutOfBoundsException
KW.java
classKW{publicstaticvoidmain(Stringargs[]){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(ArrayIndexOutOfBoundsExceptione){System.out.println("Requested element not found");}}}
Output
kodingwindow@kw:~$ javac KW.java kodingwindow@kw:~$ java KW
Array Length: 6
First Element: Mango
Last Element: Strawberry
Requested element not found
kodingwindow@kw:~$
Java program to display exception throwable details using the printStackTrace() method
KW.java
classKW{publicstaticvoidmain(Stringargs[]){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(ArrayIndexOutOfBoundsExceptione){System.out.println("Requested element not found");e.printStackTrace();System.out.println(e);}}}
Output
kodingwindow@kw:~$ javac KW.java kodingwindow@kw:~$ java KW
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 KW.main(KW.java:12)
java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 6
kodingwindow@kw:~$
Dear User, Thank you for visitng KodingWindow. If you are interested in technical articles, latest technologies, and our journey further, please follow us on LinkedIn.