Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't the ArrayIndexOutOfBoundsException a compile time error?

Can someone explain to me why ArrayIndexOutOfBoundsException is a run-time exception instead of a compile-time error? In obvious cases when the indexes are negative or greater than the array size, I don't see why it cannot be a compile-time error.

Edited: especially when the size of the array and even the indexing is known at compile time, for example int[] a = new int[10]; a[-1]=5; This should be a compilation error.

like image 798
Laz London Avatar asked May 09 '14 15:05

Laz London


2 Answers

Entering a[-1] = 5; is something only novices would do (as Richard Tingle said). So it's not worth the effort to update the language standard just for that kind of error. A more interesting case would be a[SOME_CONSTANT] = 5; where SOME_CONSTANT was defined as static final int SOME_CONSTANT = -1; (or some expression involving only constants that computes to -1) in some other class. Even then, however, if the compiler flagged this as an error, it might catch cases where the programmer has put a[SOME_CONSTANT] = 5; in an if statement that has already checked for negative values of the constant. (I'm assuming here that SOME_CONSTANT is a constant whose value could change if the application's requirements change.) So while the language could, in theory, make it illegal to write an array indexing operation that can't possibly succeed, there are good reasons not to.

P.S. This is a real issue. The Ada language does do some compile-time checking for static expressions that can't succeed, but it doesn't check this case, and there has been some discussion in the last few weeks about whether it should, or whether compilers should be allowed (but not required) to reject programs with array indexing that is known to fail.

like image 54
ajb Avatar answered Oct 23 '22 13:10

ajb


The size of the arrays may be defined only at runtime (for instance, the simplest case, if the size of an array depends on the user input).

Therefore it would be impossible to check at compile time for such kind of exceptions, by checking the accesses of an array without actually know its bounds (size).

like image 28
WoDoSc Avatar answered Oct 23 '22 14:10

WoDoSc