krahets/hello-algo · error · Error

堆疊為空

Error message

堆疊為空

What it means

Thrown by ArrayStack.pop() (message: '堆疊為空' = 'stack is empty') when the underlying array has length 0. The guard prevents JS's native pop() from returning undefined and hiding a logic error.

Source

Thrown at zh-hant/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

  1. Check stack.isEmpty() before pop().
  2. Use while (!stack.isEmpty()) for drain loops.
  3. In algorithm code, ensure every pop is matched by a prior push.

Example fix

// before
const val = stack.pop(); // throws '堆疊為空' if empty

// after
if (!stack.isEmpty()) {
    const val = stack.pop();
}
Defensive patterns

Strategy: validation

Validate before calling

if (!stack.isEmpty()) {
    const val = stack.pop();
}

Try / catch

try {
    const val = stack.pop();
} catch (e) {
    if (e.message === '堆疊為空') {
        // stack is empty — handle underflow
    } else throw e;
}

Prevention

When it happens

Trigger: Calling pop() on a stack with no elements, or popping more than was pushed.

Common situations: Unbalanced push/pop in expression evaluation; backtracking that pops past the base; DFS that exhausts the stack without checking.

Related errors


AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13). Data as JSON: /api/errors/a4e051a59e368dbf. Report an issue: GitHub.