{"record":{"id":"797b1973e7b23ada","repo":"krahets/hello-algo","slug":"stack-is-empty-797b19","errorCode":null,"errorMessage":"Stack is empty","messagePattern":"Stack is empty","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"en/codes/typescript/chapter_stack_and_queue/array_stack.ts","lineNumber":31,"sourceCode":"\n    /* Get the length of the stack */\n    get size(): number {\n        return this.stack.length;\n    }\n\n    /* Check if the stack is empty */\n    isEmpty(): boolean {\n        return this.stack.length === 0;\n    }\n\n    /* Push */\n    push(num: number): void {\n        this.stack.push(num);\n    }\n\n    /* Pop */\n    pop(): number | undefined {\n        if (this.isEmpty()) throw new Error('Stack is empty');\n        return this.stack.pop();\n    }\n\n    /* Return list for printing */\n    top(): number | undefined {\n        if (this.isEmpty()) throw new Error('Stack is empty');\n        return this.stack[this.stack.length - 1];\n    }\n\n    /* Return Array */\n    toArray() {\n        return this.stack;\n    }\n}\n\n/* Driver Code */\n/* Access top of the stack element */\nconst stack = new ArrayStack();","sourceCodeStart":13,"sourceCodeEnd":49,"githubUrl":"https://github.com/krahets/hello-algo/blob/69932aed1891a7b7f6a0de88cd116d3fe13e7032/en/codes/typescript/chapter_stack_and_queue/array_stack.ts#L13-L49","documentation":"Thrown by ArrayStack.pop when the stack is empty. pop calls Array.pop on the backing array, but the guard ensures the caller never receives undefined masquerading as a number and signals the precondition failure explicitly.","triggerScenarios":"Calling pop on a freshly created stack; popping more times than you pushed; unbalanced push/pop in expression evaluation.","commonSituations":"Algorithm implementations (e.g. parenthesis matching, DFS) that pop without checking depth; loops that assume the stack is non-empty.","solutions":["Check isEmpty() before pop.","Use while (!stack.isEmpty()) for draining.","Wrap pop to return undefined on empty instead of throwing."],"exampleFix":"// before\nconst v = stack.pop(); // throws if empty\n\n// after\nconst v = stack.isEmpty() ? undefined : stack.pop();","handlingStrategy":"validation","validationCode":"const v = stack.isEmpty() ? undefined : stack.pop();","typeGuard":"function hasElements(s) { return typeof s.isEmpty === 'function' && !s.isEmpty(); }","tryCatchPattern":"try { return stack.pop(); }\ncatch (e) { if (!/Stack is empty/.test(e.message)) throw e; return undefined; }","preventionTips":["Pair every pop with an isEmpty() check.","Track depth in algorithm loops for cheap guards.","Wrap pop in a helper returning undefined on empty."],"tags":["stack","typescript","validation","guard-clause","empty-state"],"backgroundTag":null,"analyzedSha":"69932aed1891a7b7f6a0de88cd116d3fe13e7032","analyzedAt":"2026-08-13T23:02:37.581Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}