{"record":{"id":"a4e051a59e368dbf","repo":"krahets/hello-algo","slug":"error-a4e051","errorCode":null,"errorMessage":"堆疊為空","messagePattern":"堆疊為空","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"zh-hant/codes/javascript/chapter_stack_and_queue/array_stack.js","lineNumber":31,"sourceCode":"\n    /* 獲取堆疊的長度 */\n    get size() {\n        return this.#stack.length;\n    }\n\n    /* 判斷堆疊是否為空 */\n    isEmpty() {\n        return this.#stack.length === 0;\n    }\n\n    /* 入堆疊 */\n    push(num) {\n        this.#stack.push(num);\n    }\n\n    /* 出堆疊 */\n    pop() {\n        if (this.isEmpty()) throw new Error('堆疊為空');\n        return this.#stack.pop();\n    }\n\n    /* 訪問堆疊頂元素 */\n    top() {\n        if (this.isEmpty()) throw new Error('堆疊為空');\n        return this.#stack[this.#stack.length - 1];\n    }\n\n    /* 返回 Array */\n    toArray() {\n        return this.#stack;\n    }\n}\n\n/* Driver Code */\n/* 初始化堆疊 */\nconst stack = new ArrayStack();","sourceCodeStart":13,"sourceCodeEnd":49,"githubUrl":"https://github.com/krahets/hello-algo/blob/69932aed1891a7b7f6a0de88cd116d3fe13e7032/zh-hant/codes/javascript/chapter_stack_and_queue/array_stack.js#L13-L49","documentation":"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.","triggerScenarios":"Calling pop() on a stack with no elements, or popping more than was pushed.","commonSituations":"Unbalanced push/pop in expression evaluation; backtracking that pops past the base; DFS that exhausts the stack without checking.","solutions":["Check stack.isEmpty() before pop().","Use while (!stack.isEmpty()) for drain loops.","In algorithm code, ensure every pop is matched by a prior push."],"exampleFix":"// before\nconst val = stack.pop(); // throws '堆疊為空' if empty\n\n// after\nif (!stack.isEmpty()) {\n    const val = stack.pop();\n}","handlingStrategy":"validation","validationCode":"if (!stack.isEmpty()) {\n    const val = stack.pop();\n}","typeGuard":null,"tryCatchPattern":"try {\n    const val = stack.pop();\n} catch (e) {\n    if (e.message === '堆疊為空') {\n        // stack is empty — handle underflow\n    } else throw e;\n}","preventionTips":["Check isEmpty() before pop().","Ensure every pop is matched by a prior push in algorithm code.","Use while (!stack.isEmpty()) for drain loops."],"tags":["stack","javascript","empty-state","precondition"],"backgroundTag":null,"analyzedSha":"69932aed1891a7b7f6a0de88cd116d3fe13e7032","analyzedAt":"2026-08-13T23:02:37.581Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}