{"record":{"id":"56324e5f59953eb4","repo":"krahets/hello-algo","slug":"error-56324e","errorCode":null,"errorMessage":"栈为空","messagePattern":"栈为空","errorType":"exception","errorClass":"IndexError","httpStatus":null,"severity":"error","filePath":"codes/python/chapter_stack_and_queue/array_stack.py","lineNumber":30,"sourceCode":"        \"\"\"构造方法\"\"\"\n        self._stack: list[int] = []\n\n    def size(self) -> int:\n        \"\"\"获取栈的长度\"\"\"\n        return len(self._stack)\n\n    def is_empty(self) -> bool:\n        \"\"\"判断栈是否为空\"\"\"\n        return self.size() == 0\n\n    def push(self, item: int):\n        \"\"\"入栈\"\"\"\n        self._stack.append(item)\n\n    def pop(self) -> int:\n        \"\"\"出栈\"\"\"\n        if self.is_empty():\n            raise IndexError(\"栈为空\")\n        return self._stack.pop()\n\n    def peek(self) -> int:\n        \"\"\"访问栈顶元素\"\"\"\n        if self.is_empty():\n            raise IndexError(\"栈为空\")\n        return self._stack[-1]\n\n    def to_list(self) -> list[int]:\n        \"\"\"返回列表用于打印\"\"\"\n        return self._stack\n\n\n\"\"\"Driver Code\"\"\"\nif __name__ == \"__main__\":\n    # 初始化栈\n    stack = ArrayStack()\n","sourceCodeStart":12,"sourceCodeEnd":48,"githubUrl":"https://github.com/krahets/hello-algo/blob/69932aed1891a7b7f6a0de88cd116d3fe13e7032/codes/python/chapter_stack_and_queue/array_stack.py#L12-L48","documentation":"IndexError '栈为空' (stack is empty) raised by ArrayStack.pop. Popping an empty stack would call list.pop() on an empty list (which itself raises a less descriptive error), so the guard intercepts with a clear message.","triggerScenarios":"Calling stack.pop() when the underlying list has length 0.","commonSituations":"Balanced-bracket / expression-evaluation code that pops a closing marker when none was pushed; recursion simulation via an explicit stack with a wrong termination test; calling pop twice for a single logical pop.","solutions":["Check is_empty() before pop.","Drive with while not stack.is_empty(): top = stack.pop().","When matching pairs, only pop when a matching opener is expected and present."],"exampleFix":"// before\ntop = stack.pop()  # raises when drained\n// after\ntop = stack.pop() if not stack.is_empty() else None","handlingStrategy":"validation","validationCode":"def safe_pop(stack):\n    return stack.pop() if not stack.is_empty() else None","typeGuard":"def stack_non_empty(stack) -> bool:\n    return not stack.is_empty()","tryCatchPattern":"try:\n    top = stack.pop()\nexcept IndexError:\n    top = None","preventionTips":["Check is_empty() before pop.","Use while not stack.is_empty() as the drain condition.","Only pop a matching opener when bracket matching requires it."],"tags":["stack","index-error","empty-structure","pop"],"backgroundTag":null,"analyzedSha":"69932aed1891a7b7f6a0de88cd116d3fe13e7032","analyzedAt":"2026-08-13T23:02:37.581Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}