Hi ,I am trying to implement stack with linked list ,but when I run it show up
NullPointerException
How can I avoid that with try and catch
Thanks

public char pop() {
		   try{
	      ListNode returnNode = top;
	      top = top.next;
		   } catch (Exception e){}
          return returnNode.value;
	   }

Thanks,If I do that it is giving me add return statement error

public char pop() {
		   try{
	      ListNode returnNode = top;
	      top = top.next;
	      return returnNode.value;
		   } catch (Exception e){}
          
	   }

The compiler doesn't see how a return would be done if the exception were thrown and the catch block executed. You need to add a default return.

Perhaps a better way would be to assign the value to a new char variable inside the try{}catch. If that throws an exception you can set the char variable to ???
then at the end return the char variable.

Edited 5 Years Ago by NormR1: n/a

Usually I'd do something like

public char pop(){
  ListNode return node = null;
    try {
       node = getMeANodeOrDieTrying();
       // dangerous assignment
    }
    catch (DieTryingException  dte)  // catch the specific exceptions you expect, so you can handle them correctly
    {
      notifyWidow("He knew it was a dangerous assignment");
      //handle, don't eat the exception! 
    }
    return node;  // it might still be null, but you've done your best
  }
}

Edited 5 Years Ago by jon.kiparsky: n/a

This article has been dead for over six months. Start a new discussion instead.