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.

3
  • 1
    You can find additional information about checked and uncheck exceptions here: stackoverflow.com/questions/3540613/… Commented May 9, 2017 at 10:20
  • 1
    Imagine what would happen if you would be forced to explicitly catch all possible NullPointerExceptions. Commented May 9, 2017 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.". Commented May 9, 2017 at 10:22

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.