Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 455
Omar N Avatar asked May 31 '26 18:05

Omar N


1 Answers

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
like image 168
Mena Avatar answered Jun 02 '26 09:06

Mena



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!