java - 异常情况: Incorrect Exception thrown

标签 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;

}

最佳答案

此行失败:

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

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

尝试将其更改为:

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

所以首先检查空值。

关于java - 异常情况: Incorrect Exception thrown,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18603798/

相关文章:

c# - nlog 异常布局以格式化异常类型、消息和堆栈跟踪

java - 从java应用程序动态构建oracle sql查询

java - 使用 FileCopyUtils.copy 在 Spring 上传大文件

java - 如何在 SplashScreen 之后启动另一个 Activity。启动画面在给定的计时器之后崩溃

java - 如何解决 ClassNotFoundException : com. mongodb.connection.BufferProvider?

java - 如何防止 servlet 缓冲响应内容

java - MongoDB检查连接无异常

java - 我的类(class)出现空指针错误

Java UncaughtExceptionHandler + LOG4J + Maven

c++ - 嵌套的 catch 运算符