实现Queue时Catch块报错:无法找到EmptyQueueException等类
解决Queue测试中找不到EmptyQueueException和FullQueueException的问题
你碰到的这个编译错误指向性特别明确:编译器在TestQueue类里找不到EmptyQueueException和FullQueueException这两个异常类。这俩不是Java标准库自带的异常,所以要么是你压根没创建它们,要么是创建了但没正确引入到测试类里。下面给你一步步解决的方案:
第一步:创建自定义异常类
先单独写两个异常类文件,它们需要继承自Exception(Queue任务一般用受检异常):// EmptyQueueException.java public class EmptyQueueException extends Exception { // 无参构造,带默认提示 public EmptyQueueException() { super("队列已经空啦,没法执行出队操作~"); } // 支持自定义提示信息的构造方法 public EmptyQueueException(String message) { super(message); } }// FullQueueException.java public class FullQueueException extends Exception { public FullQueueException() { super("队列已经满啦,没法执行入队操作~"); } public FullQueueException(String message) { super(message); } }注意把这两个文件和你的
TestQueue、ArrayQueue放在同一个包里;如果放在不同包,记得在TestQueue顶部加上导入语句:import 你的包路径.EmptyQueueException; import 你的包路径.FullQueueException;第二步:让ArrayQueue正确抛出这些异常
你的ArrayQueue类里的入队、出队方法得声明抛出对应的异常,不然测试类里的try-catch也抓不到。举个完整的ArrayQueue示例:public class ArrayQueue { private int[] elements; private int front; private int rear; private int size; private int capacity; public ArrayQueue(int capacity) { this.capacity = capacity; elements = new int[capacity]; front = 0; rear = -1; size = 0; } // 入队方法,满了就抛FullQueueException public void enqueue(int item) throws FullQueueException { if (isFull()) { throw new FullQueueException(); } rear = (rear + 1) % capacity; elements[rear] = item; size++; } // 出队方法,空了就抛EmptyQueueException public int dequeue() throws EmptyQueueException { if (isEmpty()) { throw new EmptyQueueException(); } int item = elements[front]; front = (front + 1) % capacity; size--; return item; } // 判断队列是否已满 public boolean isFull() { return size == capacity; } // 判断队列是否为空 public boolean isEmpty() { return size == 0; } }第三步:在TestQueue里正常捕获异常
现在你的测试类就能正确识别这两个异常类了,补全后的测试代码示例:public class TestQueue { public static void main(String[] args) { ArrayQueue Q = new ArrayQueue(3); try{ Q.enqueue(1); Q.enqueue(2); Q.enqueue(3); // 这里入队第四个元素,会触发FullQueueException Q.enqueue(4); } catch (FullQueueException e) { System.out.println(e.getMessage()); } try{ Q.dequeue(); Q.dequeue(); Q.dequeue(); // 这里出队空队列,会触发EmptyQueueException Q.dequeue(); } catch (EmptyQueueException e) { System.out.println(e.getMessage()); } } }
另外,如果你用的是IDEA、Eclipse这类IDE,遇到找不到类的错误时,直接按快捷键(比如IDEA的Alt+Enter)就能让IDE自动帮你创建这些异常类,或者自动生成导入语句,效率会更高哦~
内容的提问来源于stack exchange,提问作者Kukuriku
相关产品推荐
相关产品推荐

