Arrays.copyOfRange method in java throws incorrect exception Arrays.copyOfRange method in java throws incorrect exception arrays arrays

Arrays.copyOfRange method in java throws incorrect exception


Well, the Javadoc says :

Throws:

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

  • IllegalArgumentException - if from > to

Looking at the implementation, you can see that you got an IllegalArgumentException exception instead of ArrayIndexOutOfBoundsException due to int overflow :

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;}

This code thinks that from > to because to-from caused int overflow (due to from being Integer.MIN_VALUE), which resulted in a negative newLength.


You send Integer.MIN_VALUE(-2147483648) as from range.You probably meant to send 0 instead


You face error as MIN_VALUE = -2147483648 [0x80000000] which is negative. either u set 0 i.e. Arrays.copyOfRange(a, 0, 10); . it will allowed you to copy.