Skip to content

Commit 9129a32

Browse files
committed
feat: Add stack implementation with custom StackOverFlow and StackUnderFlow exceptions
WHAT the code does: - Defines two custom checked exceptions: - StackOverFlow → thrown when attempting to push into a full stack. - StackUnderFlow → thrown when attempting to pop from an empty stack. - Implements a fixed-size integer stack: - Fields: size (capacity), top (index pointer, initialized to -1), and array S[]. - push(int x): - Checks if stack is full (top == size - 1). - If full, throws StackOverFlow. - Otherwise, increments top and stores element. - pop(): - Checks if stack is empty (top == -1). - If empty, throws StackUnderFlow. - Otherwise, returns top element and decrements top. - Demonstrates in StackOverAndUnderFlow main(): - Creates a stack of capacity 5. - Attempts six pushes. - The sixth push triggers StackOverFlow, which is caught and printed. WHY this matters: - Reinforces understanding of stack data structures and their core operations (push, pop). - Demonstrates defensive programming using custom exceptions instead of silent errors. - Shows how to explicitly model domain-specific errors (overflow/underflow) instead of relying on built-in array bounds exceptions. - Provides a foundation for more advanced algorithms (expression evaluation, backtracking, undo/redo systems). HOW it works: 1. Stack st = new Stack(5) → allocates stack of size 5. 2. st.push() is called six times. - For first five calls, elements are successfully stored. - On sixth call, condition top == size - 1 becomes true, so push() throws new StackOverFlow(). 3. main() catches StackOverFlow and prints "Stack is Full" (from toString override). Tips and gotchas: - Always handle both overflow and underflow in custom data structures. - Catching exceptions locally (as in this demo) is fine, but in larger systems you may propagate them up for centralized handling. - For production systems, prefer java.util.Deque (ArrayDeque/LinkedList) for stack behavior. - Method naming convention: consider consistent lowercase (push, pop) with Java standards. Use-cases / analogies: - Undo operations in a text editor (stack of actions). - Evaluating arithmetic expressions using postfix notation. - Call stack simulation in interpreters or compilers. - Browser navigation history (back/forward). Short key: java stack data-structure custom-exception overflow underflow. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 97a79ec commit 9129a32

File tree

1 file changed

+1
-1
lines changed

1 file changed

+1
-1
lines changed

Section18ExceptionHandling/src/StackOverAndUnderFlow.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ public void push(int x) throws StackOverFlow {
2828
}
2929

3030
public int pop() throws StackUnderFlow {
31-
int x=-1;
31+
int x = -1;
3232

3333
if(top==-1)
3434
throw new StackUnderFlow();

0 commit comments

Comments
 (0)