I’m working with custom exceptions in Java for stack operations. However, I’m unsure if the exception handling is being handled properly, especially in terms of how exceptions are thrown and caught. Can you review this code and explain how exception handling works here? Specifically, I need guidance on the use of checked vs. unchecked exceptions and whether the exceptions (StackOverFlow and StackUnderFlow) are being used correctly.
class StackOverFlow extends Exception
{
public String toString()
{
return "Stack is Full";
}
}
class StackUnderFlow extends Exception
{
public String toString()
{
return "Stack is Empty";
}
}
class Stack
{
private int size;
private int top=-1;
private int S[];
public Stack(int sz)
{
size=sz;
S=new int[sz];
}
public void push(int x) throws StackOverFlow
{
if(top==size-1)
throw new StackOverFlow();
top++;
S[top]=x;
}
public int pop() throws StackUnderFlow
{
int x=-1;
if(top==-1)
throw new StackUnderFlow();
x=S[top];
top--;
return x;
}
}
public class StackOverAndUnderFlow
{
public static void main(String[] args)
{
Stack st=new Stack(5);
try
{
st.push(10);
st.push(15);
st.push(10);
st.push(15);
st.push(10);
st.push(15);
}
catch(StackOverFlow s)
{
System.out.println(s);
}
}
}
StackOverFlow
: This exception is thrown when an attempt is made to push an item onto a full stack.
StackUnderFlow
: This exception is thrown when an attempt is made to pop an item from an empty stack.
2. Stack Class
Fields:
size
: The maximum size of the stack.top
: Tracks the index of the top element in the stack. It's initialized to -1, indicating an empty stack.S
: An array to store the elements of the stack
Code is working fine but how do I deal such questions in interview?