Jok*_*ker 18 java arrays exception-handling exception try-catch
我今天在阵列上工作,突然间我遇到了一个抛出意外异常的场景.
如果你看下面的代码,我认为它必须抛出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] + " ");
}
}
Run Code Online (Sandbox Code Playgroud)
如果我弄错了,有人可以帮助我,让我知道吗?
Era*_*ran 21
那么,Javadoc说:
抛出:
ArrayIndexOutOfBoundsException - 如果来自<0或from> original.length
IllegalArgumentException - 如果从>到
纵观实现,你可以看到你有一个IllegalArgumentException
例外,而不是ArrayIndexOutOfBoundsException
由于int
溢出:
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;
}
Run Code Online (Sandbox Code Playgroud)
这段代码认为from
> to
因为to-from
导致int溢出(由于from
存在Integer.MIN_VALUE
),导致负面newLength
.
归档时间: |
|
查看次数: |
2749 次 |
最近记录: |