Java – how to correctly throw a NullPointerException?
I need to write a method delete (), which accepts an int parameter K and deletes the k-th element in the linked list (if any) I also want to see if the list is empty or K out of bounds If any of them is true, I want to throw a NullPointerException My code so far is as follows
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 execute it with a value 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 delete, throw a new nullpointerexception(); From my code line, I still get the same error message. When I execute the code, I know that the value will be null
My problem is that I implemented throwing a new nullpointerexception(); Is the command correct? If not, how can I fix its implementation?
Solution
First, you usually don't throw NullPointerException
This is an unchecked exception thrown when a null value is referenced, indicating a coding error rather than a recoverable condition
Secondly, when you do not explicitly throw an exception in your code, you will see it thrown anyway. Your current value is likely to be null, so current Next will throw it
You can try some explicit exceptions to throw:
>Indexoutofboundsexception > NoSuchElementException > IllegalStateException > and so on, or your own custom exception