krahets/hello-algo · error · Error
栈为空
Error message
栈为空
What it means
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.
Source
Thrown at codes/typescript/chapter_stack_and_queue/array_stack.ts:31
/* 获取栈的长度 */
get size(): number {
return this.stack.length;
}
/* 判断栈是否为空 */
isEmpty(): boolean {
return this.stack.length === 0;
}
/* 入栈 */
push(num: number): void {
this.stack.push(num);
}
/* 出栈 */
pop(): number | undefined {
if (this.isEmpty()) throw new Error('栈为空');
return this.stack.pop();
}
/* 访问栈顶元素 */
top(): number | undefined {
if (this.isEmpty()) throw new Error('栈为空');
return this.stack[this.stack.length - 1];
}
/* 返回 Array */
toArray() {
return this.stack;
}
}
/* Driver Code */
/* 初始化栈 */
const stack = new ArrayStack();View on GitHub (pinned to 69932aed18)
Solutions
- Guard with isEmpty(): if (!stack.isEmpty()) stack.pop().
- Use while (!stack.isEmpty()) for drain loops.
- Ensure balanced push/pop counts; audit sentinel handling.
Example fix
// before
const top = stack.pop(); // throws when empty
// after
if (!stack.isEmpty()) {
const top = stack.pop();
} Defensive patterns
Strategy: validation
Validate before calling
function safePop(stack) {
return stack.isEmpty() ? undefined : stack.pop();
} Type guard
null
Try / catch
null
Prevention
- Guard pop with isEmpty().
- Ensure balanced push/pop counts; audit sentinels in evaluators.
- Use while (!stack.isEmpty()) for draining.
When it happens
Trigger: Calling pop() on a freshly-constructed or fully-drained stack; an unbalanced push/pop sequence (more pops than pushes).
Common situations: Evaluation loops (expression evaluators, backtracking) that pop one extra sentinel or operator; recursion-elimination via an explicit stack that pops past empty.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/5fead45f9247928e.
Report an issue: GitHub.