The Java compiler attempts to be smart, anticipating potential exceptions and forcing you to acknowledge those potential exceptions.
Sometimes, however, Java does not detect a potential exception at compile
time, but encounters an exception at run time nevertheless. Java
compiles the following demonstration program without complaint, but throws
an ArrayIndexOutOfBoundsException
, because the array has no
element indexed by 3
:
public class Demonstrate { public static void main(String argv[]) { int [] threeElements = {1, 2, 3}; for (int counter = 0; counter < 4; ++counter) { System.out.println(threeElements[counter]); } } }