我正在阅读 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 thansrc.length
, the length of the source array.destPos+length
is greater thandest.length
, the length of the destination array.
在throws
的声明中,它说
IndexOutOfBoundsException - if copying would cause access of data outside array bounds.
我想知道...
为什么他们使用 IndexOutOfBoundsException 而不是 ArrayIndexOutOfBoundsException?
我尝试了上述所有情况,实际上都抛出了 ArrayIndexOutOfBoundsException。
那么有什么理由可以让他们避免在 JavaDoc 中使用 IndexOutOfBoundsException 的子类吗?
最佳答案
您似乎已经知道,IndexOutOfBoundsException
是 ArrayIndexOutOfBoundsException
的父类。我认为通过返回更通用的异常类型,Java 可以使其 System.arraycopy() API 更加灵活。假设将来 System.arraycopy() 抛出另一种类型的索引边界异常。如果 API 使用严格的 ArrayIndexOutOfBoundsException,那么使用该方法的任何人都可能必须重构其代码。另一方面,通过使用 IndexOutOfBoundsException,代码保持灵活,并且可以轻松处理新类型的异常。
总而言之,我想说 Java 这样做是出于良好的设计实践。
关于java - System.arraycopy 是否有抛出 IndexOutOfBoundsException 的情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41297662/