Example to to use a try/catch to prevent
ArrayIndexOutOfBoundsException:
package java_testarray;
/**
*
* @web http://java-buddy.blogspot.com/
*/
public class Java_testArray {
public static void main(String[] args) {
int[] intArray = {1, 2, 3, 4, 5};
int ans;
//ans = intArray[-1]; //java.lang.ArrayIndexOutOfBoundsException
//ans = intArray[5]; //java.lang.ArrayIndexOutOfBoundsException
for (int i = -2; i < intArray.length + 2; i++) {
try {
ans = intArray[i];
} catch (ArrayIndexOutOfBoundsException e) {
ans = 0;
}
System.out.println(i + " : " + ans);
}
}
}
 |
Prevent ArrayIndexOutOfBoundsException with try/catch |
No comments:
Post a Comment