[java] 자바 스택 구현시 예외 처리하기

스택은 후입선출(LIFO) 원칙에 따라 동작하는 자료구조입니다. 자바에서 스택을 구현할 때는 예외 처리를 고려해야 합니다. 스택에 push 또는 pop 연산을 수행할 때 예외가 발생할 수 있기 때문입니다. 이 글에서는 자바에서 스택을 구현하면서 예외 처리하는 방법에 대해 알아보겠습니다.

스택 구현하기

public class Stack {
    private int maxSize;
    private int top;
    private int[] stackArray;

    public Stack(int size) {
        maxSize = size;
        top = -1;
        stackArray = new int[maxSize];
    }

    public void push(int value) throws StackOverflowException {
        if (top == maxSize - 1) {
            throw new StackOverflowException("Stack is full, cannot push element.");
        }

        stackArray[++top] = value;
    }

    public int pop() throws StackUnderflowException {
        if (top == -1) {
            throw new StackUnderflowException("Stack is empty, cannot pop element.");
        }

        return stackArray[top--];
    }

    public boolean isEmpty() {
        return top == -1;
    }

    public boolean isFull() {
        return top == maxSize - 1;
    }
}

위 코드는 자바에서 스택을 구현한 예시입니다. Stack 클래스는 최대 크기를 지정하여 생성되며, pushpop 메서드로 요소를 추가하고 제거합니다. 스택이 비어있는 경우 StackUnderflowException 예외가 발생하고, 스택이 가득 찬 경우 StackOverflowException 예외가 발생합니다.

스택 예외 처리하기

public class StackOverflowException extends Exception {
    public StackOverflowException(String message) {
        super(message);
    }
}

public class StackUnderflowException extends Exception {
    public StackUnderflowException(String message) {
        super(message);
    }
}

위 코드는 StackOverflowExceptionStackUnderflowException 예외 클래스를 정의한 예시입니다. 각 예외 클래스는 생성자에서 예외 메시지를 전달받아 초기화하고, Exception 클래스를 상속받아 예외 처리를 가능하게 합니다.

사용 예시

public class Main {
    public static void main(String[] args) {
        Stack stack = new Stack(5);

        try {
            stack.push(1);
            stack.push(2);
            stack.push(3);
            stack.push(4);
            stack.push(5);
            // stack.push(6);  // StackOverflowException 발생

            while (!stack.isEmpty()) {
                System.out.println(stack.pop());
            }

            // stack.pop();  // StackUnderflowException 발생
        } catch (StackOverflowException e) {
            System.out.println("Stack overflow: " + e.getMessage());
        } catch (StackUnderflowException e) {
            System.out.println("Stack underflow: " + e.getMessage());
        }
    }
}

위 예시 코드에서는 Stack 객체를 생성한 후에 push 메서드로 요소를 추가하고, pop 메서드로 요소를 제거합니다. 스택이 가득 찬 경우 StackOverflowException 예외가 발생하고, 스택이 비어있는 경우 StackUnderflowException 예외가 발생합니다. 예외 발생 시 getMessage 메서드를 통해 예외 메시지를 출력할 수 있습니다.

결론

자바에서 스택을 구현할 때는 예외 처리를 고려해야 합니다. 이를 통해 프로그램이 예외 상황을 처리하고 올바르게 동작할 수 있습니다. 스택을 활용하는 애플리케이션에서는 적절한 예외 처리를 통해 안정성을 높이는 것이 좋습니다.

참고 자료