Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays.copyOfRange method in java throws incorrect exception

I was working on arrays today and suddenly I came across a scenario throwing unexpected exceptions.

If you look at the code below , I think it must throw ArrayIndexOutOfBoundsException, but surprisingly it is throwing IllegalArgumentException instead:

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] + " ");
   }
}

Can anybody help me and let me know if I am mistaken?

like image 530
Sachin Sachdeva Avatar asked Dec 29 '15 09:12

Sachin Sachdeva


People also ask

What does arrays copyOfRange do in Java?

copyOfRange(short[] original, int from, int to) method copies the specified range of the specified array into a new array. The final index of the range (to), which must be greater than or equal to from, may be greater than original.

What is arrays fill in Java?

fill() method is in java. util. Arrays class. This method assigns the specified data type value to each element of the specified range of the specified array.

What can you do with arrays in Java?

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.


1 Answers

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.

like image 59
Eran Avatar answered Sep 17 '22 15:09

Eran