{"record":{"id":"5fead45f9247928e","repo":"krahets/hello-algo","slug":"error-5fead4","errorCode":null,"errorMessage":"栈为空","messagePattern":"栈为空","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"codes/typescript/chapter_stack_and_queue/array_stack.ts","lineNumber":31,"sourceCode":"\n    /* 获取栈的长度 */\n    get size(): number {\n        return this.stack.length;\n    }\n\n    /* 判断栈是否为空 */\n    isEmpty(): boolean {\n        return this.stack.length === 0;\n    }\n\n    /* 入栈 */\n    push(num: number): void {\n        this.stack.push(num);\n    }\n\n    /* 出栈 */\n    pop(): number | undefined {\n        if (this.isEmpty()) throw new Error('栈为空');\n        return this.stack.pop();\n    }\n\n    /* 访问栈顶元素 */\n    top(): number | undefined {\n        if (this.isEmpty()) throw new Error('栈为空');\n        return this.stack[this.stack.length - 1];\n    }\n\n    /* 返回 Array */\n    toArray() {\n        return this.stack;\n    }\n}\n\n/* Driver Code */\n/* 初始化栈 */\nconst stack = new ArrayStack();","sourceCodeStart":13,"sourceCodeEnd":49,"githubUrl":"https://github.com/krahets/hello-algo/blob/69932aed1891a7b7f6a0de88cd116d3fe13e7032/codes/typescript/chapter_stack_and_queue/array_stack.ts#L13-L49","documentation":"Thrown by ArrayStack.pop() ('栈为空' / stack is empty) when the underlying array has length 0. pop() calls Array.pop which would return undefined, but the explicit guard rejects that as an error to avoid returning undefined where a number is expected.","triggerScenarios":"Calling pop() on a freshly-constructed or fully-drained stack; an unbalanced push/pop sequence (more pops than pushes).","commonSituations":"Evaluation loops (expression evaluators, backtracking) that pop one extra sentinel or operator; recursion-elimination via an explicit stack that pops past empty.","solutions":["Guard with isEmpty(): if (!stack.isEmpty()) stack.pop().","Use while (!stack.isEmpty()) for drain loops.","Ensure balanced push/pop counts; audit sentinel handling."],"exampleFix":"// before\nconst top = stack.pop(); // throws when empty\n// after\nif (!stack.isEmpty()) {\n    const top = stack.pop();\n}","handlingStrategy":"validation","validationCode":"function safePop(stack) {\n  return stack.isEmpty() ? undefined : stack.pop();\n}","typeGuard":"null","tryCatchPattern":"null","preventionTips":["Guard pop with isEmpty().","Ensure balanced push/pop counts; audit sentinels in evaluators.","Use while (!stack.isEmpty()) for draining."],"tags":["typescript","stack","empty-state","validation"],"backgroundTag":null,"analyzedSha":"69932aed1891a7b7f6a0de88cd116d3fe13e7032","analyzedAt":"2026-08-13T23:02:37.581Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}