简体   繁体   中英

How to properly throw nullPointerException?

I need to write a method delete() that takes an int argument k and deletes the kth element in the linked list, if it exists. I also want to watch when the list is empty, or k is out of bounds. If either of those are true, I want to throw a NullPointerException . The code I have so far is below.

    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;  
  }

When I go to execute it with a value that I know will be null, I get the following output:

Exception in thread "main" 
java.lang.NullPointerException
at hw4.LinkedList.delete(LinkedList.java:168)
at hw4.LLTest1.main(LLTest1.java:23)

However, if I remove the throw new NullPointerException(); line from my code, I still get that same error message when executing the code with a value that I know will be null.

My question is, am I implementing the throw new NullPointerException(); command correctly, and if not, how can I fix my implementation of it?

Firstly, you don't typically throw a NullPointerException .

This is an unchecked exception thrown when referencing a null value, which indicates a coding error rather than a recoverable condition.

Secondly, when you're not explicitly throwing the exception in your code, yet seeing it thrown anyway, it's likely that your value for current is null , hence current.next would throw it.

You could try a number of explicit exceptions to throw:

  • IndexOutOfBoundsException
  • NoSuchElementException
  • IllegalStateException
  • Etc. etc., or your own custom exception

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM