gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:42:15 26 4
gpt4 key购买 nike

我正在阅读 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com