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

Recommended Answers

All 6 Replies

You need to move the return statement inside the try/catch block.

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.

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

which propably works better with :

public char pop(){
  ListNode node = null;
  ..
}

:)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.