TheAlgorithms/Java · error · IllegalStateException
MinPriorityQueue is empty. Cannot peek.
Error message
MinPriorityQueue is empty. Cannot peek.
What it means
Thrown by MinPriorityQueue.peek() when isEmpty() returns true. The queue stores the minimum at heap[1] using 1-based array indexing, so peeking an empty queue would read an uninitialized slot. The guard enforces the non-empty precondition before reading the root.
Source
Thrown at src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java:69
if (this.heap[k] < this.heap[k / 2]) {
int temp = this.heap[k];
this.heap[k] = this.heap[k / 2];
this.heap[k / 2] = temp;
}
k = k / 2;
}
this.size++;
}
/**
* Retrieves the highest priority value (the minimum) without removing it.
*
* @return the minimum value in the queue
* @throws IllegalStateException if the queue is empty
*/
public int peek() {
if (isEmpty()) {
throw new IllegalStateException("MinPriorityQueue is empty. Cannot peek.");
}
return this.heap[1];
}
/**
* Checks whether the queue is empty.
*
* @return true if the queue is empty, false otherwise
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Checks whether the queue is full.
*
* @return true if the queue is full, false otherwise
*/View on GitHub (pinned to fdfb9a395b)
Solutions
- Guard with isEmpty(): `return pq.isEmpty() ? OptionalInt.empty() : OptionalInt.of(pq.peek());`.
- Ensure at least one insert precedes any peek.
- Catch IllegalStateException and return a sentinel/empty result.
- Structure the consumer to only run after the producer signals population.
Example fix
// before
int min = pq.peek();
// after
if (pq.isEmpty()) {
return OptionalInt.empty();
}
return OptionalInt.of(pq.peek()); Defensive patterns
Strategy: validation
Validate before calling
if (!pq.isEmpty()) {
return pq.peek();
}
return OptionalInt.empty(); Try / catch
try {
return OptionalInt.of(pq.peek());
} catch (IllegalStateException e) {
return OptionalInt.empty();
} Prevention
- Guard peek with isEmpty().
- Return an Optional-like result to callers.
- Ensure a producer has populated the queue before the consumer peeks.
When it happens
Trigger: Calling peek on a freshly constructed queue with no inserts. Calling peek after draining all elements via delete.
Common situations: Polling a queue that may not yet be populated by a producer. Top-of-loop read before the first insert. Empty-input edge case in a merge or scheduling algorithm.
Related errors
- MinPriorityQueue is empty. Cannot delete.
- Cannot extract from empty heap
- Cannot delete from empty heap
- Queue is Empty
- Cannot insert null element
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/cbc189c413b460fe.
Report an issue: GitHub.