I'm trying to check if an array location is out of bounds, what's the simplest way?
int[] arr;
populate(arr);
if(arr[-1] == null)
//out of bounds!
Would something like this work?
I'm pretty sure this can be done with a trycatch or a scanner but for just a simple small program, is there another way?
Simply use: boolean inBounds = (index >= 0) && (index < array. length); Implementing the approach with try-catch would entail catching an ArrayIndexOutOfBoundsException , which is an unchecked exception (i.e. a subclass of RuntimeException ).
The StringIndexOutOfBoundsException is an unchecked exception in Java that occurs when an attempt is made to access the character of a string at an index which is either negative or greater than the length of the string.
When your program is running and it tries to access an element of an array, the Java virtual machine checks that the array element actually exists. This is called bounds checking.
As a Java program is running, each time an array index is used it is checked to be sure that it is OK. This is called bounds checking, and is extremely important for catching errors.
Absolutely do not use try-catch for this. Simply use:
boolean inBounds = (index >= 0) && (index < array.length);
Implementing the approach with try-catch would entail catching an ArrayIndexOutOfBoundsException
, which is an unchecked exception (i.e. a subclass of RuntimeException
). Such exceptions should never (or, at least, very rarely) be caught and dealt with. Instead, they should be prevented in the first place.
In other words, unchecked exceptions are exceptions that your program is not expected to recover from. Now, there can be exceptions (no pun intended) to this here and there. For instance, it has become common practice to check if a string is parable as an integer by calling Integer.parseInt()
on it and catching the potential NumberFormatException
(which is unchecked). This is considered OK, but always think twice before doing something like that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With