异常条件:抛出不正确的异常

时间:2013-09-04 00:59:33

标签: java exception

我的家庭作业有问题。我们的在线分配网站评分,我一直收到以下关于我在下面显示的代码的错误。

错误:

Exception conditions. Incorrect exception thrown for null a.java.lang.NullPointerException
  public static int[] nearestK(int[] a, int val, int k) {

  int x = 0;

  if (k < x || a.length == 0 || a == null)
  {
     throw new IllegalArgumentException("k is not invalid");
  }

  if (k == 0 || k > a.length) 
  {
     int[] incorrect = new int[0];
     return incorrect ;
  }

  final int value = val; 
  Integer[] copy = new Integer[a.length]; 
  for (int i = 0; i < a.length; i++) {
     copy[i] = a[i];
  }

  Arrays.sort(copy, 
        new Comparator<Integer>() {                   
           @Override
           public int compare(Integer o1, Integer o2) {
              int distance1 = Math.abs(value - o1); 
              int distance2 = Math.abs(value - o2); 
              return Integer.compare(distance1, distance2);
           }
        });

  int[] answer = new int[k]; 
  for (int i = 0; i < answer.length; i++) {
     answer[i] = copy[i];
  }

  return answer;

}

2 个答案:

答案 0 :(得分:2)

这一行失败了:

if (k < x || a.length == 0 || a == null)

因为a.length会在有机会检查a == null之前抛出NullPointerException。

尝试将其更改为:

if (a == null || k < x || a.length == 0)

所以首先检查null。

答案 1 :(得分:0)

 if (k < x || a.length == 0 || a == null)

这需要反过来,因为它是从左到右进行评估的,并且空检查需要保护长度检查。

实际上,a.length会产生空指针异常。

  if (k < x || a == null || a.length == 0)

通过这个序列,评估不会一直向右(这就是短路算子||所做的那样)。

相关问题