krahets/hello-algo · error · Error

スタックが空です

Error message

スタックが空です

What it means

Thrown by pop() on the array-backed stack when `isEmpty()` is true (stack.length === 0). Plain Error. Note the return type is `number | undefined`, but on empty it throws rather than returning undefined — a contract mismatch callers often miss.

Source

Thrown at ja/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. Always gate with `if (!stack.isEmpty())` or `while (!stack.isEmpty())`.
  2. Wrap in try/catch where empty is expected and recoverable.
  3. Do not rely on the `| undefined` return type as an emptiness signal — it throws first.

Example fix

// before
const v = stack.pop();

// after
const v = stack.isEmpty() ? undefined : stack.pop();
Defensive patterns

Strategy: validation

Validate before calling

// Guard stack pop.
if (!stack.isEmpty()) {
  const v = stack.pop();
}

Type guard

function stackCanPop(stack) {
  return !stack.isEmpty();
}

Try / catch

try {
  const v = stack.pop();
} catch (e) {
  if (e instanceof Error && e.message === 'スタックが空です') {
    // empty stack
  } else throw e;
}

Prevention

When it happens

Trigger: Calling pop() on a freshly constructed empty stack; popping more times than you pushed; popping in a loop without an isEmpty exit.

Common situations: Unbalanced push/pop pairs (e.g. a recursive descent with an early-return path that skips a push but still pops); assuming pop returns undefined on empty because of the `| undefined` signature; draining a stack built from filtered input that can be empty.

Related errors


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