2

I would like to inquire the reason (rule in Java's design) that makes dealing with Arrays such as:

public static void main(String args[]){
System.out.println(args[2]);
}

not requiring a try and catch for ArrayIndexOutOfBoundsException?

Are there some exceptions that are implicitly always method-throws assigned by javac or is javac simply inconsistent here?

Any answer would be appreciated to provide some references to he design specs/docu about this behaviour.

humanityANDpeace
  • 4,350
  • 3
  • 37
  • 63
  • 1
    You can find additional information about checked and uncheck exceptions here: http://stackoverflow.com/questions/3540613/please-explain-runtimeexception-in-java-and-where-it-should-be-used โ€“ Tobi May 09 '17 at 10:20
  • 1
    Imagine what would happen if you would be forced to explicitly catch all possible NullPointerExceptions. โ€“ Tobi May 09 '17 at 10:22
  • The key point to me is there: "Use checked exceptions for conditions from which the caller can reasonably be expected to recover" vs. "Use runtime exceptions to indicate programming errors.". โ€“ dounyy May 09 '17 at 10:22

2 Answers2

1

ArrayIndexOutOfBoundsException is a sub-class of RuntimeException, which makes it an unchecked exceptions. Unchecked exception don't need to be caught, and don't need to be declared in a throws clause.

This is stated in the Javadoc of RuntimeException:

RuntimeException and its subclasses are unchecked exceptions. Unchecked exceptions do not need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

That has been discussed in JLS # 10.4. Array Access

All array accesses are checked at run time; an attempt to use an index that is less than zero or greater than or equal to the length of the array causes an ArrayIndexOutOfBoundsException to be thrown (ยง15.10.4).

https://docs.oracle.com/javase/specs/jls/se8/html/jls-10.html#jls-10.4

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307