簡體   English   中英

是否有任何情況System.arraycopy拋出IndexOutOfBoundsException?

[英]Is there any circumstance that System.arraycopy throws IndexOutOfBoundsException?

我正在閱讀System.arraycopyJavaDoc ,發現有些困惑。

...如果滿足以下任一條件,則拋出IndexOutOfBoundsException ,並且不修改目標:

  • srcPos參數為負。
  • destPos參數為負。
  • length參數為負。
  • srcPos+length大於源數組的長度src.length
  • destPos+length大於目標數組的長度dest.length

throws的語句中,它說

IndexOutOfBoundsException-如果復制將導致超出數組范圍的數據訪問。

我很好奇...
為什么他們使用IndexOutOfBoundsException但不使用ArrayIndexOutOfBoundsException?
我嘗試了上述所有情況,並且實際上都拋出了ArrayIndexOutOfBoundsException。
那么,有什么理由可以避免在JavaDoc中使用IndexOutOfBoundsException的子類?

如您所知, IndexOutOfBoundsExceptionArrayIndexOutOfBoundsException的父類。 我認為,通過返回更通用的異常類型,Java可以使其System.arraycopy() API更加靈活。 假設將來System.arraycopy()拋出另一種類型的索引范圍異常。 如果API使用了嚴格的ArrayIndexOutOfBoundsException則使用該方法的任何人可能都必須重構其代碼。 另一方面,通過使用IndexOutOfBoundsException ,代碼保持了靈活性,並且可以以最小的麻煩處理新類型的異常。

因此,總而言之,我要說Java是出於良好的設計實踐而進行的。

從javadoc:

  • ArrayIndexOutOfBoundsException

    拋出該錯誤指示數組已使用非法索引訪問。 索引為負或大於或等於數組的大小。

  • IndexOutOfBoundsException

    表示某種索引(例如,數組,字符串或向量)的索引超出范圍。

任何索引超出范圍時,將引發IndexOutOfBoundsException ,而當數組索引超出范圍時,將引發ArrayIndexOutOfBoundsException

通過拋出ArrayIndexOutOfBoundsException ,他們可以清楚地知道索引是什么-特別是數組索引。 如果他們拋出IndexOutOfBoundsException ,則可以引用任何索引。

Tl; dr:他們變得更加具體和清晰。

至於為什么文檔說它拋出IndexOutOfBoundsException卻實際上拋出ArrayIndexOutOfBoundsException

ArrayIndexOutOfBoundsException確實從IndexOutOfBoundsException擴展而來,因此可以在IndexOutOfBoundsException下對其進行分類,並且更容易簡單地引用超類,但最終會拋出ArrayIndexOutOfBoundsException因為它更精確。 您還可以在try / catch塊中使用IndexOutOfBoundsException ,而不是ArrayIndexOutOfBoundsException ,這使從System.arrayCopy()捕獲異常更加容易,但是在捕獲異常時也變得更加具體。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM