java如何在队列中使用异常
public class ArrayQueue{
private Object[] theArray;
private int currentSize;
private int front;
private int rear;
static final int DEFAULT_CAPACITY=10;
public ArrayQueue(){
theArray=new Object[DEFAULT_CAPACITY];
makeEmpty();
}
public void makeEmpty(){
currentSize=0;
rear=-1;
front=0;
}
public void enqueue(Object x) throws OverFlow{
if (isFull())
throw new OverFlow("Array size exceeded");
else{
rear=increment(rear);
theArray[rear]=x;
currentSize++;
}
}
public Object dequeue()throws UnderFlow{
if (isEmpty())
throw new UnderFlow("Empty array");
else{
Object returnValue=theArray[front];
theArray[front]=null;//check if this has to be done
front=increment(front);
currentSize--;
return returnValue;
}
}
public Object getFront() throws UnderFlow{
if (isEmpty())
throw new UnderFlow("Empty array");
else
return theArray[front];
}
public boolean isEmpty(){
if (currentSize==0)
return true;
else
return false;
}
public boolean isFull(){
if (currentSize==theArray.length)
return true;
else
return false;
}
public int increment(int x){
if (x+1==currentSize)
x=0;
else
x++;
return x;
}
public static void main (String args[]){
ArrayQueue q=new ArrayQueue();
q.enqueue("1");
}
}
public class OverFlow extends Exception{
public OverFlow(){
super();
}
public OverFlow(String s){
super(s);
}
}
public class UnderFlow extends Exception{
public UnderFlow(){
super();
}
public UnderFlow(String s){
super(s);
}
}
当我尝试运行这个程序时,我得到一个错误,即未报告的异常溢出,必须被捕获或声明为抛出
我不熟悉Java和编程,但我必须学习数据结构课程。因此,如果有人能告诉我这里出了什么问题以及如何纠正它,这将是非常有帮助的
# 1 楼答案
任何扩展
Exception
(除了RuntimeException
)的类都是considered a checked exception。这意味着您,程序员,必须要么在try...catch
块中捕获它,要么在其他地方抛出异常问题是你的方法
enqueue()
抛出了一个选中的异常您可以通过以下两种方式之一解决此问题:
enqueue
的调用包装在try...catch
块中,或throws OverFlow
添加到main
李>这两个例子都有: