I want to check whether the given coordinates are withing an array or not.
public boolean checkBounds(int x, int y) {
try {
Object val = array[x][y];
return true;
} catch (ArrayIndexOutOfBoundsException e) {
return false;
}
}
Can I do it like that? Is it an efficient way to do it?
What happens when we use exceptions to perform boundary checks?
Using exceptions for handling operations like null checking, bounds checking, file existance checking introduces a lot of overhead whenever the exception is thrown.
What you would have done if you simply checked the bounds:
What you actually are doing when using exception-based checking:
Performance comparison
With this simple test program, I have measured the speed of both types of array boundary checks.
The results:
JDK 7, eclipse
Run as
mode:JDK 7, eclipse
Debug
mode:The speed loss with debugging disabled is not very significant, though it is visible: code without exceptions is about 30% faster (for roughly 50% of false returns). The speed loss in debug mode is astonishing. The exception-based code runs about 700 times slower than the normal straight-up array size check.
Philosophy of exceptions
The general idea behind exceptions is to allow a way to handle exceptiona conditions. In this case, there is no exceptional condition at all - the range check is just a normal part of code. For that reason alone the exception should not be used in this situation.