Sub topic 7
Underflow, overflow, and error handling
This chapter assumes you can write Python classes, know what a list is, and understand Big-O notation. It also assumes you have seen a stack with push, pop, and peek. Here we look at what happens when those operations are called at the edges: on an empty stack, and on a stack that cannot grow.
Underflow: popping from an empty stack
Underflow happens when you pop or peek on a stack that has no items. There is nothing to return, so the operation has no valid result. The common mistake is to hide this by returning a placeholder such as None.
class SilentStack:
def __init__(self):
self._items = []
def push(self, item):
self._items.append(item)
def pop(self):
if not self._items:
return None # ambiguous
return self._items.pop()
s = SilentStack()
s.push(None)
print(s.pop()) # None: a real item
print(s.pop()) # None: underflow, but it looks the sameThe caller cannot tell a stored None from an empty stack. Errors pass silently and show up later, far from the cause. Raising an exception avoids this.
class Stack:
def __init__(self):
self._items = []
def push(self, item):
self._items.append(item)
def pop(self):
if not self._items:
raise IndexError("pop from empty stack")
return self._items.pop()
def peek(self):
if not self._items:
raise IndexError("peek at empty stack")
return self._items[-1]
def is_empty(self):
return not self._items
stack = Stack()
try:
stack.pop()
except IndexError as error:
print("Caught:", error)IndexError matches what Python's own list.pop() raises, so callers already know how to handle it.
Choosing an error strategy
There are three common ways to report underflow. Pick one and use it consistently.
| Strategy | Example | Trade-off |
|---|---|---|
| Raise an exception | `raise IndexError` | Cannot be ignored by accident. Needs `try`/`except`. |
| Return a sentinel | `return None` | Simple, but ambiguous if `None` is a valid item. |
| Check first | `if not s.is_empty():` | Explicit, but the caller must remember to do it. |
Checking first is fine for single-threaded code. In concurrent code, another thread can empty the stack between your check and your pop(). Catching the exception is safer there.
Overflow: pushing onto a full stack
Overflow happens when a push has no room left. There are two cases.
- Bounded stack. You set a maximum capacity on purpose, for example to limit memory use. A push beyond the limit must fail.
- Fixed-size array. In languages such as C, a stack built on a fixed array overflows when the array is full.
A Python list grows automatically, so it only fails if the process runs out of memory. A bounded stack is easy to build:
class BoundedStack:
def __init__(self, capacity):
if capacity < 1:
raise ValueError("capacity must be at least 1")
self._capacity = capacity
self._items = []
def push(self, item):
if len(self._items) >= self._capacity:
raise OverflowError("push onto full stack")
self._items.append(item)
def pop(self):
if not self._items:
raise IndexError("pop from empty stack")
return self._items.pop()
s = BoundedStack(2)
s.push("a")
s.push("b")
try:
s.push("c")
except OverflowError as error:
print("Caught:", error)The state is unchanged after a failed push. That matters: an operation that fails should leave the stack as it was.
Overflow in the call stack
The same word describes a different failure in the call stack. When recursion goes too deep, Python raises RecursionError, and in languages like Java you get StackOverflowError. This is overflow of the runtime's own stack, covered in the call stack chapter.
Common errors
- Returning
Nonefrompop()whenNonecan be a valid item. - Calling
peek()without checking for an empty stack first. - Modifying the stack before detecting an error, which leaves it half-updated.
- Catching a broad
Exceptionand hiding underflow bugs.
Exercise
A stack stores user-entered values, and None is a valid value. Why is returning None from pop() on an empty stack a bad design, and what should pop() do instead?
Show answer
The caller cannot distinguish a popped None from underflow. pop() should raise an exception such as IndexError("pop from empty stack"), so the error cannot be ignored by accident.
Exercise
In BoundedStack, why does push check the length before calling append?
Show answer
So that a full stack is detected before any change is made. The failed push raises OverflowError and leaves the stack contents unchanged.