如何正确抛出nullPointerException?

Oma*_*r N 3 java linked-list

我需要编写一个delete()带有int参数k 的方法,并删除链表中的第k个元素(如果存在).我也想看看列表是空的,还是k超出界限.如果其中任何一个都是真的,我想扔一个NullPointerException.我到目前为止的代码如下.

    public void delete(int k){
      Node current = head;
      for (int i = 0; i < k; i++){
          if(head == null && current.next == null){
              throw new NullPointerException();
              }
          else 
          {
              current = current.next; // Move pointer to k position
          }
      }
      remove(current.item);
      --N;  
  }
Run Code Online (Sandbox Code Playgroud)

当我用一个我知道将为null的值执行它时,我得到以下输出:

Exception in thread "main" 
java.lang.NullPointerException
at hw4.LinkedList.delete(LinkedList.java:168)
at hw4.LLTest1.main(LLTest1.java:23)
Run Code Online (Sandbox Code Playgroud)

但是,如果我throw new NullPointerException();从我的代码中删除该行,我仍然会在执行代码时得到相同的错误消息,其中我知道该值将为null.

我的问题是,我throw new NullPointerException();是否正确地执行了命令,如果没有,我该如何修复它的实现呢?

Men*_*ena 11

首先,你通常不会抛出一个NullPointerException.

这是在引用null值时抛出的未经检查的异常,该值表示编码错误而不是可恢复的条件.

其次,当你没有明确地在你的代码中抛出异常,但是无论如何都看到它被抛出,你的价值可能currentnull,因此current.next会抛出它.

你可以尝试一些显式异常来抛出:

  • IndexOutOfBoundsException
  • NoSuchElementException
  • IllegalStateException
  • 等等,或您自己的自定义异常