In: Computer Science
Part 1:Write a program in Java that declares an array of 5 elements and displays the contents of the array. Your program should attempt to access the 6th element in the array (which does not exist) and using try. catch your program should prevent the run-time error and display your error message to the user. The sample output including the error message is provided below.
Part (1) Printing an element out of bounds
5
7
11
3
0
You went out of limits in the array
/*If you any query do comment in the comment section else like the solution*/
public class ArrayLimit {
public static void main(String[] args) {
int arr[] = {1, 2, 3, 4, 5};
try {
for(int i=0;i<=5;i++) {
System.out.println(arr[i]);
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("You went out of limits in the array");
}
}
}