java - System.arraycopy 是否有抛出 IndexOutOfBoundsException 的情况?

标签 java indexoutofboundsexception

我正在阅读 JavaDoc System.arraycopy 并发现一些让我困惑的东西。

... if any of the following is true, an IndexOutOfBoundsException is thrown and the destination is not modified:

  • The srcPos argument is negative.
  • The destPos argument is negative.
  • The length argument is negative.
  • srcPos+length is greater than src.length, the length of the source array.
  • destPos+length is greater than dest.length, the length of the destination array.

throws的声明中,它说

IndexOutOfBoundsException - if copying would cause access of data outside array bounds.

我想知道...
为什么他们使用 IndexOutOfBoundsException 而不是 ArrayIndexOutOfBoundsException?
我尝试了上述所有情况,实际上都抛出了 ArrayIndexOutOfBoundsException。
那么有什么理由可以让他们避免在 JavaDoc 中使用 IndexOutOfBoundsException 的子类吗?

最佳答案

您似乎已经知道,IndexOutOfBoundsExceptionArrayIndexOutOfBoundsException 的父类。我认为通过返回更通用的异常类型,Java 可以使其 System.arraycopy() API 更加灵活。假设将来 System.arraycopy() 抛出另一种类型的索引边界异常。如果 API 使用严格的 ArrayIndexOutOfBoundsException,那么使用该方法的任何人都可能必须重构其代码。另一方面,通过使用 IndexOutOfBoundsException,代码保持灵活,并且可以轻松处理新类型的异常。

总而言之,我想说 Java 这样做是出于良好的设计实践。

关于java - System.arraycopy 是否有抛出 IndexOutOfBoundsException 的情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41297662/

相关文章:

java - notifyDataSetChanged() 没有调用 onBindViewHolder

Java-数组索引越界异常

java - java 获取 ArrayIndexOutOfBoundsException

java - 委托(delegate)给线程,同时保持线性可读性

java - 如何检查用户输入是否为 double ?

java - Java使用什么技巧来避免>>中的空格?

java - 线程中的异常 "main"java.lang.ArrayIndexOutOfBoundsException : 160

Java 线程 ArrayIndexOutOfBoundsException

Java 数组!不!越界

java - maven-remote-resources-plugin 不复制文件,仅复制文件夹结构