本文介绍了java中的Arrays.copyOfRange方法抛出不正确的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你看下面的代码,我认为它必须抛出$ code> 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);
//如果我们将使用Integer.MIN_VALUE + 100替代Integer.MIN_VALUE,
// OutOfMemoryError将抛出
(int k = 0; k System.out.print(b [k] +);
}
}

有人可以帮助我,让我知道,如果我是错误?

解决方案

嗯,Javadoc说:

看看实现,你可以看到你有一个 IllegalArgumentException exception而不是 ArrayIndexOutOfBoundsException 由于 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));
返回副本;
}

此代码认为到导致int溢出(由于 Integer.MIN_VALUE ),导致消极的 newLength


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?

解决方案

Well, the Javadoc says :

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.

这篇关于java中的Arrays.copyOfRange方法抛出不正确的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 18:19