What happens when a thrown exception is not handled?
What happens when a thrown exception is not handled?
Share
When an exception occurred, if you don’t handle it, the program terminates abruptly and the code past the line that caused the exception will not get executed.
Example
Generally, an array is of fixed size and each element is accessed using the indices. For example, we have created an array with size 7. Then the valid expressions to access the elements of this array will be a[0] to a[6] (length-1).
Whenever, you used an –ve value or, the value greater than or equal to the size of the array, then the ArrayIndexOutOfBoundsException is thrown.
For Example, if you execute the following code, it displays the elements in the array asks you to give the index to select an element. Since the size of the array is 7, the valid index will be 0 to 6.
Example
import java.util.Arrays;
import java.util.Scanner;
public class EXPSample {
public static void main(String args[]){
int[] myArrayList = {1255, 1459, 5688,1458, 4555, 5446, 7525};
System.out.println(“Elements in the array are: “);
System.out.println(Arrays.toString(myArrayList));
Scanner sc = new Scanner(System.in);
System.out.println(“Enter the index of the required element: “);
int element = sc.nextInt();
System.out.println(“Element in the given index is :: “+myArrayList[element]);
}
}
But if you observe the below output we have requested the element with the index 9 since it is an invalid index an ArrayIndexOutOfBoundsException raised and the execution terminated.
Run time exception
Elements in the array are:
[897, 56, 78, 90, 12, 123, 75]
Enter the index of the required element:
7
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 7
at EXPSample.main(EXPSample.java:12)
Solution
To resolve this, you need to handle the exception by wrapping the code responsible for it, in a try-catch block.
import java.util.Arrays;
import java.util.Scanner;
public class EXPSample {
public static void main(String args[]){
int[] myArrayList = {1255, 1459, 5688,1458, 4555, 5446, 7525};
System.out.println(“Elements in the array are: “);
System.out.println(Arrays.toString(myArrayList));
try {
Scanner sc = new Scanner(System.in);
System.out.println(“Enter the index of the required element: “);
int element = sc.nextInt();
System.out.println(“Element in the given index is :: “+myArrayList[element]);
}catch(ArrayIndexOutOfBoundsException ex) {
System.out.println(“Please enter the valid index 0 to 6”);
}
}
}
Output
Elements in the array are:
[1254, 1458, 5687, 1457, 4554, 5445, 7524]
Enter the index of the required element:
7
Please enter the valid index (0 to 6)