krahets/hello-algo · error · Error

堆疊為空

Error message

堆疊為空

What it means

An Error '堆疊為空' ('stack is empty') thrown by pop() in ArrayStack (array_stack.ts:31). pop() delegates to the native Array.pop after an emptiness check; without the guard, popping an empty JS array returns undefined, which the typed number return would mask as a logic bug. The check makes the failure explicit.

Source

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

  1. Check stack.isEmpty() before pop.
  2. Loop with `while (!stack.isEmpty())` when draining.
  3. Track the number of pushes and never pop more than that.
  4. Wrap pop in a helper returning undefined when empty if that is the desired contract.

Example fix

// before: popping an empty stack throws
const top = stack.pop();

// after: guard with emptiness check
const top = stack.isEmpty() ? undefined : stack.pop();
Defensive patterns

Strategy: validation

Validate before calling

// Guard ArrayStack pop
function safePop(stack: ArrayStack): number | undefined {
    return stack.isEmpty() ? undefined : stack.pop();
}
while (!stack.isEmpty()) {
    const top = stack.pop();
}

Type guard

const nonEmpty = (stack: ArrayStack): boolean => !stack.isEmpty();

Try / catch

try {
    const top = stack.pop();
} catch (e) {
    if (e instanceof Error && e.message === '堆疊為空') {
        // stack empty; handle gracefully
    } else throw e;
}

Prevention

When it happens

Trigger: Calling stack.pop() when stack.isEmpty() is true (this.stack.length === 0). Popping more times than you pushed, or popping a freshly constructed `new ArrayStack()`.

Common situations: Mismatched push/pop counts; unbalanced parentheses/bracket matching that pops on a close token with nothing on the stack; DFS/undo implementations that pop without checking depth; reusing a stack instance after draining it.

Related errors


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