//....
int vals[] = new int [12];
vals[18] = 10;
catch (ArrayIndexOutofBoundsException) {
//handle error
...
}
//....
int vals[] = new int [12];
vals[18] = 10;
catch (ArrayIndexOutofBoundsException) {
//handle error
...
}
The immediate bug is an out‑of‑bounds access: you created an array with 12 slots but try to write past the last element. Java arrays are zero‑based, so allocating 12 elements gives valid indices 0 through 11. already noted that — writing to index 18 will throw an ArrayIndexOutOfBoundsException at runtime (see the official javadoc).
There are two additional issues to fix in the sample. First, the catch clause shown is syntactically wrong: Java is case‑sensitive and a catch must declare an exception variable (for example, catch (ArrayIndexOutOfBoundsException e) { ... }). Second, the exception class for arrays is ArrayIndexOutOfBoundsException; collections typically use IndexOutOfBoundsException. is right that a catch will prevent a crash, but relying on exceptions for normal control flow is poor practice.
Scope is another gotcha: if you declare the array inside the try block it won’t be visible afterwards, as mentioned. Declare the variable in an outer scope if you need it after the try. Better still, prevent the exception by checking the index against vals.length before assigning, or use a dynamically sized collection (e.g., ArrayList) when you don’t know the needed capacity.
References: Java arrays and zero‑based indexes are covered in the Java Tutorial on arrays (https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html), and the ArrayIndexOutOfBoundsException javadoc explains the thrown condition (https://docs.oracle.com/javase/8/docs/api/java/lang/ArrayIndexOutOfBoundsException.html).
Jump to Post— jwenting 1,905at least the exception will be handled :)
youve only made your array size 12 as in
int vals[0]
int vals[1]
int vals[2]
int vals[3]
int vals[4]
int vals[5]
int vals[6]
int vals[7]
int vals[8]
int vals[9]
int vals[10]
int vals[11]
so you can have vals[18]
at least the exception will be handled :)
You also need to enclose it in a try/catch block
try {
int vals[] = new int [12];
vals[18] = 10;
} catch (ArrayIndexOutofBoundsException) {
//handle error
} Note - since you create the vals[] array in the try/catch block the vals[] array will not be available after the try/catch (see scope documentation on try/catch)
To avoid this declare your member variables outside the block:
int vals[] = new int [12];
try {
vals[18] = 10;
} catch (ArrayIndexOutofBoundsException) {
//handle error
} We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.