我正在编写一个队列类,并且已经编写了接口和队列类,并已被指示编写一个处理空异常和完全异常的异常类。当我们的类执行堆栈程序时,我们为StackFullException和StackEmptyException都有单独的类,我知道如何编写这些类,但我并不真正理解如何将它组合成一个QueueException类。
到目前为止,这就是我所拥有的
public class QueueException extends Exception {
public QueueEmptyException() {
super("Stack is empty");
}
public QueueFullException() {
super("Stack is full");
}
public QueueException(String msg) {
super(msg);
}
}发布于 2018-04-08 19:24:47
你离我很近!将它们分成多个类(如QueueEmptyException和QueueFullException )是个好主意,但是如果您真的想将它们组合成一个类,那么只需要一个构造函数:
public class QueueException extends Exception {
public QueueException(String msg) {
super(msg);
}
}当您想要抛出此异常时,您可以调用这两个异常中的任何一个:
throw new QueueException("Queue is full!");
throw new QueueException("Queue is empty!");发布于 2018-04-08 19:45:15
你能做的就是使用继承。
所以创建一个新的类QueueException
public class QueueException extends Exception {
public QueueException(String msg) {
super(msg);
}
}让您的QueueEmptyException和QueueFullException继承QueueException而不是Exception
public class QueueEmptyException extends QueueException{
public QueueEmptyException() {
super("Queue is empty");
}
}在实际抛出异常的方法中,可以执行以下操作:
public void someMethodThrowingQueueExceptions() throws QueueException{
//some logic
//throw here either a full or empty exception
throw new QueueEmptyException();
}https://stackoverflow.com/questions/49721817
复制相似问题