[英]Arrays.copyOfRange method in java throws incorrect exception
我今天在陣列上工作,突然間我遇到了一個拋出意外異常的場景。
如果你看下面的代碼,我認為它必須拋出ArrayIndexOutOfBoundsException
,但令人驚訝的是它拋出了IllegalArgumentException
:
import java.util.Arrays;
public class RangeTest {
public static void main(String[] args) {
int[] a = new int[] {0,1,2,3,4,5,6,7,8,9};
int[] b = Arrays.copyOfRange(a, Integer.MIN_VALUE, 10);
// If we'll use Integer.MIN_VALUE+100 instead Integer.MIN_VALUE,
// OutOfMemoryError will be thrown
for (int k = 0; k < b.length; k++)
System.out.print(b[k] + " ");
}
}
如果我弄錯了,有人可以幫助我,讓我知道嗎?
那么,Javadoc說:
拋出:
ArrayIndexOutOfBoundsException - 如果來自<0或from> original.length
IllegalArgumentException - 如果從>到
查看實現,您可以看到由於int
溢出而導致IllegalArgumentException
異常而不是ArrayIndexOutOfBoundsException
:
public static int[] copyOfRange(int[] original, int from, int to) {
int newLength = to - from;
if (newLength < 0)
throw new IllegalArgumentException(from + " > " + to);
int[] copy = new int[newLength];
System.arraycopy(original, from, copy, 0,
Math.min(original.length - from, newLength));
return copy;
}
此代碼認為from
> to
因為to-from
導致int溢出(由於from
Integer.MIN_VALUE
),這導致負newLength
。
您從范圍發送Integer.MIN_VALUE(-2147483648)。 你可能打算發送0代替
您面臨的錯誤為MIN_VALUE = -2147483648 [0x80000000],為負數。 或者你設置0即Arrays.copyOfRange(a, 0, 10);
。 它會允許你復制。
java Docs和實現之間存在未匹配
正如Eran所展示的那樣,由於int溢出,我們可以看到我們得到了一個IllegalArgumentException異常而不是ArrayIndexOutOfBoundsException。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.