[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");
}

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!