TheAlgorithms/Python · error · Exception
UNDERFLOW
Error message
UNDERFLOW
What it means
CircularQueue.dequeue raises a generic Exception('UNDERFLOW') when self.size == 0, i.e. dequeuing before any enqueue or after the queue has been drained. front/rear are modular indices over a fixed array; size is the authoritative emptiness signal.
Source
Thrown at data_structures/queues/circular_queue.py:103
>>> cq = CircularQueue(5)
>>> cq.dequeue()
Traceback (most recent call last):
...
Exception: UNDERFLOW
>>> cq.enqueue("A").enqueue("B").dequeue()
'A'
>>> (cq.size, cq.first())
(1, 'B')
>>> cq.dequeue()
'B'
>>> cq.dequeue()
Traceback (most recent call last):
...
Exception: UNDERFLOW
"""
if self.size == 0:
raise Exception("UNDERFLOW")
temp = self.array[self.front]
self.array[self.front] = None
self.front = (self.front + 1) % self.n
self.size -= 1
return temp
View on GitHub (pinned to f5988cc097)
Solutions
- Guard with 'if cq.size > 0:' or expose an is-empty check before dequeue.
- Catch generic Exception and match message 'UNDERFLOW' where the empty case is legitimate.
- Track produced/consumed counts on the caller side for worker loops.
Example fix
# before item = cq.dequeue() # Exception: UNDERFLOW # after item = cq.dequeue() if cq.size else None
Defensive patterns
Strategy: validation
Validate before calling
item = cq.dequeue() if cq.size > 0 else None
Try / catch
try:
item = cq.dequeue()
except Exception as e:
if 'UNDERFLOW' not in str(e):
raise
item = None Prevention
- Check cq.size > 0 before dequeuing; size is the authoritative emptiness signal.
- Generic Exception means you must match the message text.
- Pair every producer increment with at most one consume.
When it happens
Trigger: Two dequeues after one enqueue; dequeuing a fresh CircularQueue(n); a consumer loop that pops more items than were produced.
Common situations: Polling consumers without an emptiness check; misreading first()/peek semantics as consuming; porting from collections.deque.popleft (IndexError) or queue.Queue.get (blocks) and catching the wrong thing.
Related errors
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/09eba99f4d67d6d8.
Report an issue: GitHub.