Java 处理数组的代码不需要尝试捕获 ArrayIndexOutOfBoundsException 的原因?
Reason that Java code dealing with Arrays not requiring try-catch for ArrayIndexOutOfBoundsException?
我想询问处理数组的原因(Java 设计中的规则),例如:
public static void main(String args[]){
System.out.println(args[2]);
}
不需要为 ArrayIndexOutOfBoundsException
试一试?
是否有一些异常总是由 javac
分配的隐式方法-throws
或者 javac 在这里不一致?
如能提供有关此行为的设计 specs/docu 的一些参考,我们将不胜感激。
ArrayIndexOutOfBoundsException
是 RuntimeException
的子 class,这使其成为未经检查的异常。未经检查的异常不需要被捕获,也不需要在 throws 子句中声明。
这在 RuntimeException
的 Javadoc 中有说明:
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.
这已在 JLS # 10.4 中讨论过。数组访问
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
我想询问处理数组的原因(Java 设计中的规则),例如:
public static void main(String args[]){
System.out.println(args[2]);
}
不需要为 ArrayIndexOutOfBoundsException
试一试?
是否有一些异常总是由 javac
分配的隐式方法-throws
或者 javac 在这里不一致?
如能提供有关此行为的设计 specs/docu 的一些参考,我们将不胜感激。
ArrayIndexOutOfBoundsException
是 RuntimeException
的子 class,这使其成为未经检查的异常。未经检查的异常不需要被捕获,也不需要在 throws 子句中声明。
这在 RuntimeException
的 Javadoc 中有说明:
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.
这已在 JLS # 10.4 中讨论过。数组访问
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