[Solution] Exception in thread main java.util.EmptyStackException


Exception in thread "main" java.util.EmptyStackException
 at java.util.Stack.peek(Stack.java:102)
 at java.util.Stack.pop(Stack.java:84)
 at com.company.PostFixExpression.solveExpression(PostFixExpression.java:49)
 at com.company.PostFixExpression.main(PostFixExpression.java:14)

If you will try to pop an element out from the Stack Collection in Java when it is empty, you will get EmptyStackException exception. Vector peek() throws this exception if the stack is empty.

Fix:

EmptyStackException is a Runtime Exception and as for all Runtime Exceptions, it is the duty of the developer to handle it. So before you pop an element out from the Stack, check if the Stack object is empty or not.

Example: Throw a custom exception
Stack stack = new Stack();

if(stack.isEmpty()) {
 throw new Exception("Stack is empty.. nothing to pop");
}
Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.