Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting ArrayIndexOutOfBound exception for array length

Is there a way i can set a try and catch ArrayIndexOutOfBound exception to check if the array size is greater than 3? For example if the parameter array args[] holds more than 3 values, then i want the exception to show an error.

Here is my code so far:

public static void main (String[] args){
try {
    args[4] = "four";
    } catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Array index out of bounds.");
    }
}
like image 295
jeeps95 Avatar asked Jun 20 '26 04:06

jeeps95


1 Answers

You can use args.length to get the number of elements in the array.

like image 143
brso05 Avatar answered Jun 22 '26 17:06

brso05