The following code shows an Example of Custom Exception for Stack Class in Java.
Problem Statement
Create an application that throws exceptions if the stack is full or is empty.
Solution
// Custom exception class for a full stack
class StackFullException extends Exception {
public StackFullException(String message) {
super(message);
}
}
// Custom exception class for an empty stack
class StackEmptyException extends Exception {
public StackEmptyException(String message) {
super(message);
}
}
// Stack class representing a stack data structure
class Stack {
private int maxSize;
private int[] stackArray;
private int top;
public Stack(int size) {
this.maxSize = size;
this.stackArray = new int[maxSize];
this.top = -1;
}
// Method to push an element onto the stack
public void push(int value) throws StackFullException {
if (top == maxSize - 1) {
throw new StackFullException("Stack is full. Cannot push element.");
}
stackArray[++top] = value;
}
// Method to pop an element from the stack
public int pop() throws StackEmptyException {
if (isEmpty()) {
throw new StackEmptyException("Stack is empty. Cannot pop element.");
}
return stackArray[top--];
}
// Method to check if the stack is empty
public boolean isEmpty() {
return top == -1;
}
}
// Main class to demonstrate the program
public class StackExceptionDemo {
public static void main(String[] args) {
Stack stack = new Stack(3);
try {
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println("Popped: " + stack.pop()); // Popped: 3
System.out.println("Popped: " + stack.pop()); // Popped: 2
System.out.println("Popped: " + stack.pop()); // Popped: 1
System.out.println("Popped: " + stack.pop()); // Attempt to pop when stack is empty
} catch (StackFullException | StackEmptyException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}
In this program:
- We create two custom exception classes,
StackFullException
andStackEmptyException
, to represent scenarios where the stack is full or empty, respectively. - The
Stack
class represents a stack data structure with a fixed size. It has methods for pushing elements onto the stack (push
), popping elements from the stack (pop
), and checking if the stack is empty (isEmpty
). These methods throw the custom exceptions when appropriate. - In the
main
method, we create an instance of theStack
class with a size of 3. We push three elements onto the stack, pop them, and then attempt to pop when the stack is empty. We catch the custom exceptions (StackFullException
andStackEmptyException
) and print the exception messages.
This program demonstrates how to throw and catch custom exceptions when the stack is full or empty.
Further Reading
Spring Framework Practice Problems and Their Solutions
From Google to the World: The Story of Go Programming Language
Why Go? Understanding the Advantages of this Emerging Language
Creating and Executing Simple Programs in Go