From 61f94eed561c69a21a345edf81995acdac1cb680 Mon Sep 17 00:00:00 2001 From: chinmaychahar Date: Fri, 9 Oct 2020 19:13:18 +0530 Subject: [PATCH] Stack implementation using exception handling in java --- Stacks/Stack-exceptionhandling.java | 54 +++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Stacks/Stack-exceptionhandling.java diff --git a/Stacks/Stack-exceptionhandling.java b/Stacks/Stack-exceptionhandling.java new file mode 100644 index 0000000..42bde0e --- /dev/null +++ b/Stacks/Stack-exceptionhandling.java @@ -0,0 +1,54 @@ +// Stack implementation using exception handling to manage underflow and overflow conditions +class StackException extends Exception { + + StackException( String message) + { + super(message); + } +} + +class ArrayStack { + public static int[] item; + public static int stackTop; + + ArrayStack( ) + { + item = new int[4]; + stackTop=-1; + } + + static void push(int x) throws StackException { + if (stackTop==item.length-1) { + throw new StackException("Stack overflow"); + } + stackTop++; + item[stackTop] = x; + } + + static void pop( ) throws StackException { + int returnItem; + if ( stackTop==-1) { + throw new StackException("Stack underflow"); + } + returnItem = item[stackTop--]; + System.out.println(returnItem); + } +} + +class Demo { +public static void main( String args[] ) { + + ArrayStack s=new ArrayStack(); + try + { + for(int i=0;i<4;i++) + s.push(i); + for(int j=0;j<5;j++) + s.pop(); + } + + catch ( StackException e ) { + System.out.println("Error detected: " + e.getMessage() ); + } +} +} \ No newline at end of file