java - How to properly throw nullPointerException? -


i need write method delete() takes int argument k , deletes kth element in linked list, if exists. want watch when list empty, or k out of bounds. if either of true, want throw nullpointerexception. code have far below.

    public void delete(int k){       node current = head;       (int = 0; < k; i++){           if(head == null && current.next == null){               throw new nullpointerexception();               }           else            {               current = current.next; // move pointer k position           }       }       remove(current.item);       --n;     } 

when go execute value know null, following output:

exception in thread "main"  java.lang.nullpointerexception @ hw4.linkedlist.delete(linkedlist.java:168) @ hw4.lltest1.main(lltest1.java:23) 

however, if remove throw new nullpointerexception(); line code, still same error message when executing code value know null.

my question is, implementing throw new nullpointerexception(); command correctly, , if not, how can fix implementation of it?

firstly, don't typically throw nullpointerexception.

this unchecked exception thrown when referencing null value, indicates coding error rather recoverable condition.

secondly, when you're not explicitly throwing exception in code, yet seeing thrown anyway, it's value current null, hence current.next throw it.

you try number of explicit exceptions throw:

  • indexoutofboundsexception
  • nosuchelementexception
  • illegalstateexception
  • etc. etc., or own custom exception

Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -