To access elements in an array in Java using a try
-catch
block, you can use the try
block to attempt to access the element at a specific index, and the catch
block to handle any exceptions that may be thrown.
Here's an example of how you could do this:
int[] arr = {1, 2, 3, 4, 5}; try { int element = arr[5]; // try to access the element at index 5 System.out.println("Element: " + element); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Array index out of bounds: " + e.getMessage()); }Source:wwl.wautturi.com
In this example, the try
block attempts to access the element at index 5 of the arr
array. However, the array only has 5 elements, so the index 5 is out of bounds and an ArrayIndexOutOfBoundsException
is thrown. The catch
block catches this exception and prints an error message to the console.
You can use a similar approach to access other elements in the array, by specifying the index of the element you want to access in the try
block. For example:
try { int element = arr[3]; // try to access the element at index 3 System.out.println("Element: " + element); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Array index out of bounds: " + e.getMessage()); }
In this case, the try
block will access the element at index 3 of the arr
array, which is the fourth element .