Blog |

How to Fix the Empty Stack Exception in Java

How to Fix the Empty Stack Exception in Java
Table of Contents

The EmptyStackException is a runtime exception in Java that is thrown by methods in the Stack class to indicate that the stack is empty.

Since the EmptyStackException is an unchecked exception, it does not need to be declared in the throws clause of a method or constructor.

 

What Causes EmptyStackException

The EmptyStackException is thrown when attempting to access elements in an empty stack in Java. For example, if the Stack.pop() method is used to remove an object at the top of an empty stack, an EmptyStackException is thrown.

 

EmptyStackException Example

Here is an example of an EmptyStackException thrown when an element is attempted to be popped from an empty stack:

import java.util.Stack;

public class EmptyStackExceptionExample {
    public static void main(String args[]) {
        Stack s = new Stack();
        s.pop();
    }
}

The Stack.pop() method removes the element at the top of a stack. Since the above code attempts to use this method on an empty stack, it throws an EmptyStackException:

Exception in thread "main" java.util.EmptyStackException
    at java.base/java.util.Stack.peek(Stack.java:101)
    at java.base/java.util.Stack.pop(Stack.java:83)
    at EmptyStackExceptionExample.main(EmptyStackExceptionExample.java:6)

 

How to Fix EmptyStackException

The EmptyStackException can be avoided using a check to make sure that the stack is not empty before using methods such as Stack.pop() or Stack.peek() which could throw an EmptyStackException.

The code in the earlier example can be updated to include this check:

import java.util.Stack;

public class EmptyStackExceptionExample {
    public static void main(String args[]) {
        Stack s = new Stack();

        if (!s.isEmpty()) {
            s.pop();
        }

        System.out.println("Continuing execution...");
    }
}

The above code avoids the exception and produces the correct output as expected:

Continuing execution...

 

Track, Analyze and Manage Errors With Rollbar

Rollbar in action

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

Related Resources

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape