gpt4 book ai didi

java - java 中的 Arrays.copyOfRange 方法抛出不正确的异常

转载 作者:太空狗 更新时间:2023-10-29 22:38:58 25 4
gpt4 key购买 nike

我今天在做数组,突然遇到一个抛出意外异常的场景。

如果您查看下面的代码,我认为它必须抛出 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 说:

Throws:

  • ArrayIndexOutOfBoundsException - if from < 0 or from > original.length

  • IllegalArgumentException - if from > to

查看实现,您可以看到由于 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 溢出(由于 fromInteger.MIN_VALUE),这导致了负的 newLength

关于java - java 中的 Arrays.copyOfRange 方法抛出不正确的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34507935/

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