krahets/hello-algo · error · Error
栈为空
Error message
栈为空
What it means
Thrown by pop() on an array-backed stack (ArrayStack) when the stack is empty (internal #stack.length === 0). pop() calls the native Array.pop after the guard; without the check, Array.pop would return undefined and the caller could mistake that for a value. This guard makes underflow explicit.
Source
Thrown at codes/javascript/chapter_stack_and_queue/array_stack.js:31
/* 获取栈的长度 */
get size() {
return this.#stack.length;
}
/* 判断栈是否为空 */
isEmpty() {
return this.#stack.length === 0;
}
/* 入栈 */
push(num) {
this.#stack.push(num);
}
/* 出栈 */
pop() {
if (this.isEmpty()) throw new Error('栈为空');
return this.#stack.pop();
}
/* 访问栈顶元素 */
top() {
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
- Check stack.isEmpty() before pop(): if (!stack.isEmpty()) stack.pop();.
- Use a counted pop tied to a recorded push count.
- In DFS, only pop a frame you pushed; assert the stack is non-empty before processing.
- Prefer returning a sentinel (e.g. undefined or null) via a wrapper instead of relying on the throw for control flow.
Example fix
// before const top = stack.pop(); // throws if empty // after const top = stack.isEmpty() ? null : stack.pop();
Defensive patterns
Strategy: validation
Validate before calling
function safePop(stack) {
return stack.isEmpty() ? null : stack.pop();
} Type guard
function stackNotEmpty(stack) {
return !stack.isEmpty();
} Try / catch
try {
const x = stack.pop();
} catch (e) {
if (e instanceof Error && e.message === '栈为空') { /* underflow */ } else throw e;
} Prevention
- Check stack.isEmpty() before pop().
- Only pop frames you pushed in DFS/backtracking.
- Use a counted pop tied to a recorded push count.
- Wrap pop() in a helper returning a sentinel on empty.
When it happens
Trigger: Calling pop() on a freshly constructed stack; popping more than was pushed; mismatched push/pop in a balanced-parentheses or DFS routine.
Common situations: Expression evaluation (too many operators); backtracking/DFS unwind past the start; reversing with push-all then pop-too-many.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/74680344fcd8c1cd.
Report an issue: GitHub.