TheAlgorithms/Java · error · IllegalStateException

Queue is empty, cannot peek front

Error message

Queue is empty, cannot peek front

What it means

Thrown by Queue.peekFront() as an IllegalStateException when isEmpty(). The method returns queueArray[front] without removing it; with nItems == 0 there is no valid front to read. Read-only underflow guard.

Source

Thrown at src/main/java/com/thealgorithms/datastructures/queues/Queue.java:87

            throw new IllegalStateException("Queue is empty, cannot remove element");
        }
        T removedElement = (T) queueArray[front];
        queueArray[front] = null; // Optional: Clear the reference for garbage collection
        front = (front + 1) % maxSize;
        nItems--;
        return removedElement;
    }

    /**
     * Checks the element at the front of the queue without removing it.
     *
     * @return Element at the front of the queue.
     * @throws IllegalStateException if the queue is empty.
     */
    @SuppressWarnings("unchecked")
    public T peekFront() {
        if (isEmpty()) {
            throw new IllegalStateException("Queue is empty, cannot peek front");
        }
        return (T) queueArray[front];
    }

    /**
     * Checks the element at the rear of the queue without removing it.
     *
     * @return Element at the rear of the queue.
     * @throws IllegalStateException if the queue is empty.
     */
    @SuppressWarnings("unchecked")
    public T peekRear() {
        if (isEmpty()) {
            throw new IllegalStateException("Queue is empty, cannot peek rear");
        }
        return (T) queueArray[rear];
    }

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Check isEmpty() before peekFront() and return null/Optional in the empty case.
  2. Seed the queue with at least one insert() before the first peekFront().
  3. Catch IllegalStateException when emptiness is a legitimate control-flow path.

Example fix

// before
T head = queue.peekFront(); // throws when empty

// after
T head = queue.isEmpty() ? null : queue.peekFront();
Defensive patterns

Strategy: validation

Validate before calling

T head = queue.isEmpty() ? null : queue.peekFront();

Type guard

null

Try / catch

null

Prevention

When it happens

Trigger: Calling peekFront() on a newly constructed Queue, or after every inserted element has been removed(). peekFront never changes occupancy, so an empty queue always throws.

Common situations: Inspecting the next element for routing/throttling before producers have inserted; startup health checks that peek before seeding; tests asserting front state without data.

Related errors


AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13). Data as JSON: /api/errors/1618a5f16d8d0ac5. Report an issue: GitHub.