问题描述
我正在测试这个堆栈实现(带有链表),到目前为止,只要堆栈不为空,我就可以顺利进行推送,弹出和窥视。
但是,当我尝试使用带有空数组的EmptyStackException的try catch块运行此代码时,它不会捕获。
运行此命令时:
打印“ 1”,然后出现NullPointerException。
这是我的代码部分,负责从堆栈中弹出项目:
我在这里做错什么了吗?
解决方法
但是,当我尝试使用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;
}
,
在堆栈为空时,pop()
方法中的任何地方实际上都不会抛出EmptyStackException
。