krahets/hello-algo · error · Error

队列为空

Error message

队列为空

What it means

Thrown by peek() on an array-backed circular queue when the queue is empty (queSize === 0). pop() calls peek() first, so both throw identically. peek() returns #nums[#front]; on an empty queue that slot holds stale data, hence the guard.

Source

Thrown at codes/javascript/chapter_stack_and_queue/array_queue.js:57

        // 通过取余操作实现 rear 越过数组尾部后回到头部
        const rear = (this.#front + this.size) % this.capacity;
        // 将 num 添加至队尾
        this.#nums[rear] = num;
        this.#queSize++;
    }

    /* 出队 */
    pop() {
        const num = this.peek();
        // 队首指针向后移动一位,若越过尾部,则返回到数组头部
        this.#front = (this.#front + 1) % this.capacity;
        this.#queSize--;
        return num;
    }

    /* 访问队首元素 */
    peek() {
        if (this.isEmpty()) throw new Error('队列为空');
        return this.#nums[this.#front];
    }

    /* 返回 Array */
    toArray() {
        // 仅转换有效长度范围内的列表元素
        const arr = new Array(this.size);
        for (let i = 0, j = this.#front; i < this.size; i++, j++) {
            arr[i] = this.#nums[j % this.capacity];
        }
        return arr;
    }
}

/* Driver Code */
/* 初始化队列 */
const capacity = 10;
const queue = new ArrayQueue(capacity);

View on GitHub (pinned to 69932aed18)

Solutions

  1. Check queue.isEmpty() (size === 0) before peek/pop.
  2. Drain with while (!q.isEmpty()) q.pop();.
  3. Track enqueued count and never dequeue beyond it.
  4. For producer/consumer flow, signal completion instead of relying on the throw.

Example fix

// before
const head = q.peek(); // throws if empty
// after
const head = q.isEmpty() ? null : q.peek();
Defensive patterns

Strategy: validation

Validate before calling

function safePeek(q) {
  return q.isEmpty() ? null : q.peek();
}

Type guard

function queueNotEmpty(q) {
  return q.size > 0;
}

Try / catch

try {
  const head = q.peek();
} catch (e) {
  if (e instanceof Error && e.message === '队列为空') { /* handle empty */ } else throw e;
}

Prevention

When it happens

Trigger: Calling peek()/pop() on a freshly constructed queue; dequeuing more items than were enqueued; drain loop without an emptiness check.

Common situations: BFS level processing; task queue drained faster than it is filled; mismatched enqueue/dequeue counts across async boundaries.

Related errors


AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13). Data as JSON: /api/errors/912e1c30b2eed1eb. Report an issue: GitHub.