{"record":{"id":"3e8e28e0b6a660de","repo":"krahets/hello-algo","slug":"error-3e8e28","errorCode":null,"errorMessage":"队列为空","messagePattern":"队列为空","errorType":"exception","errorClass":"IndexError","httpStatus":null,"severity":"error","filePath":"codes/python/chapter_stack_and_queue/array_queue.py","lineNumber":51,"sourceCode":"        # 计算队尾指针，指向队尾索引 + 1\n        # 通过取余操作实现 rear 越过数组尾部后回到头部\n        rear: int = (self._front + self._size) % self.capacity()\n        # 将 num 添加至队尾\n        self._nums[rear] = num\n        self._size += 1\n\n    def pop(self) -> int:\n        \"\"\"出队\"\"\"\n        num: int = self.peek()\n        # 队首指针向后移动一位，若越过尾部，则返回到数组头部\n        self._front = (self._front + 1) % self.capacity()\n        self._size -= 1\n        return num\n\n    def peek(self) -> int:\n        \"\"\"访问队首元素\"\"\"\n        if self.is_empty():\n            raise IndexError(\"队列为空\")\n        return self._nums[self._front]\n\n    def to_list(self) -> list[int]:\n        \"\"\"返回列表用于打印\"\"\"\n        res = [0] * self.size()\n        j: int = self._front\n        for i in range(self.size()):\n            res[i] = self._nums[(j % self.capacity())]\n            j += 1\n        return res\n\n\n\"\"\"Driver Code\"\"\"\nif __name__ == \"__main__\":\n    # 初始化队列\n    queue = ArrayQueue(10)\n\n    # 元素入队","sourceCodeStart":33,"sourceCodeEnd":69,"githubUrl":"https://github.com/krahets/hello-algo/blob/69932aed1891a7b7f6a0de88cd116d3fe13e7032/codes/python/chapter_stack_and_queue/array_queue.py#L33-L69","documentation":"IndexError '队列为空' (queue is empty) raised by ArrayQueue.peek, and propagated by pop which calls peek first. Reading the front slot of an empty circular queue would return stale data, so the guard short-circuits.","triggerScenarios":"Calling queue.peek() or queue.pop() when _size == 0.","commonSituations":"BFS that pops after exhausting the queue; producer/consumer where the consumer starts before any push; off-by-one drain loop popping n+1 items.","solutions":["Guard with is_empty() before peek or pop.","Drive consumption with while not q.is_empty(): item = q.pop().","For optional access, expose a get-or-default wrapper."],"exampleFix":"// before\nfront = q.peek()  # raises on empty\n// after\nfront = q.peek() if not q.is_empty() else None","handlingStrategy":"validation","validationCode":"def safe_peek(q):\n    return q.peek() if not q.is_empty() else None","typeGuard":"def queue_non_empty(q) -> bool:\n    return not q.is_empty()","tryCatchPattern":"try:\n    front = q.peek()\nexcept IndexError:\n    front = None","preventionTips":["Drive consumers with while not q.is_empty().","Return a sentinel for optional front reads.","Avoid popping more items than were pushed."],"tags":["queue","circular-array","index-error","empty-structure","peek"],"backgroundTag":null,"analyzedSha":"69932aed1891a7b7f6a0de88cd116d3fe13e7032","analyzedAt":"2026-08-13T23:02:37.581Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}