为什么我的EmptyStackException没有被捕获?

问题描述

我正在测试这个堆栈实现(带有链表),到目前为止,只要堆栈不为空,我就可以顺利进行推送,弹出和窥视。

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

运行此命令时:

let country = 'India'
let city = 'Delhi'


function CreateCustomID(country,city) {
  return `${country.slice(0,2).toupperCase()}${city.slice(0,2).toupperCase()}${Math.floor(Math.random()*(999-100+1)+100)}`
}


console.log(CreateCustomID(country,city))

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

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

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");
        }
    }
}

在这里做错什么了吗?

解决方法

但是,当我尝试使用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