【问题标题】:Why is my EmptyStackException not catching here?为什么我的 EmptyStackException 没有在这里捕获?
【发布时间】:2020-12-30 12:45:39
【问题描述】:

我正在测试我拥有的这个堆栈实现(使用链表),到目前为止,只要堆栈不为空,我在推送、弹出和查看时都没有遇到任何问题。

但是,当我尝试使用带有空数组的 EmptyStackException 的 try catch 块运行此代码时,它不会捕获。

当我运行这个时:

public class Run {
    public static void main(String[] args) {
        Stack<String> stack = new Stack<String>();
        //test empty stack
        if(stack.isEmpty())
            System.out.println("1");
        try {
            stack.pop();
        } catch (EmptyStackException e) {
            System.out.println("2");
        }
    }
}

打印出“1”,然后出现NullPointerException。

这是我的代码中负责从堆栈中弹出项目的部分:

    public Item pop() throws EmptyStackException{
        s--;
        Item prevFirst = first.item;
        first = first.next;
        return firstVal;
    }

我在这里做错了吗?

【问题讨论】:

    标签: java linked-list nullpointerexception stack


    【解决方案1】:

    但是,当我尝试使用 try catch 块运行此代码时 EmptyStackException 带有一个空数组,它不会捕获。

    因为pop() 不会抛出任何东西。 在你的pop() 方法中,你应该检查堆栈大小,如果它是空的,那么你可以实例化一个异常(EmptyStackException)并抛出它。

    所以你的代码应该是这样的:

    public Item pop()throws EmptyStackException{
    
        // Check if the stack is empty or not
        if (s == 0){
            throw new EmptyStackException();
        }
    
        s--; 
           
        Item prevFirst = first.item;
        first = first.next;
        return firstVal;
    }
    

    【讨论】:

      【解决方案2】:

      pop() 方法中没有任何地方在堆栈为空时实际上会抛出 EmptyStackException

      【讨论】:

      • 那么我该如何添加呢?抱歉,我对在 Java 中执行此操作不是很熟悉。我只是假设在代码顶部添加它会起作用。
      • 在方法签名中添加throws EmptyStackException 只是告诉编译器该方法可能会抛出该异常。在方法本身中,如果堆栈为空,您仍然需要在某个时间点 throw new EmptyStackException()
      猜你喜欢
      • 1970-01-01
      • 2018-05-31
      • 1970-01-01
      • 1970-01-01
      • 2010-12-25
      • 1970-01-01
      • 2016-03-15
      • 2021-10-21
      • 1970-01-01
      相关资源
      最近更新 更多