I’m learning java, I’m supposed to add an exception handler to a class for a fixed queue. It seems the interface needs to be changed but I’m not sure how.
Code:
//ICharQ.java
package qpack;
public interface ICharQ {
void put(char ch);
char get();
void reset();
}
//QExcDemo.java
package qpack;
class QueueFullException extends Exception {
int size;
QueueFullException(int s) { size = s; }
public String toString() {
return "\nQueue is full. Max size is " + size;
}
}
class QueueEmptyException extends Exception {
public String toString() {
return "\nQueue is empty.";
}
}
//Excerpt from IQClasses.java
package qpack;
class FixedQueue implements ICharQ {
private char q[];
private int putloc, getloc;
public FixedQueue(int size) {
q = new char[size+1];
putloc = getloc = 0;
}
public void put(char ch)
throws QueueFullException {
if (putloc == q.length-1)
throw new QueueFullException(q.length-1);
putloc++;
q[putloc] = ch;
}
public char get()
throws QueueEmptyException {
if (getloc == putloc)
throw new QueueEmptyException();
getloc++;
return q[getloc];
}
public void reset() {
putloc = getloc = 0;
}
}
Compiler output…
qpack/IQClasses.java:22: error: get() in FixedQueue cannot implement get() in ICharQ
public char get()
^
overridden method does not throw QueueEmptyException
qpack/IQClasses.java:12: error: put(char) in FixedQueue cannot implement put(char) in ICharQ
public void put(char ch)
^
overridden method does not throw QueueFullException
2 errors
In FixedQueue you have the checked exceptions.
This means your interface for these method has to have the same “throws”.
BTW I would make
QueueFullExceptionandQueueEmptyExceptionextend IllegalStateException which is not a check exception, but I would still add it to the throws clause in your interface.For comparison, you could look at the Queue and I would follow the naming and exceptions it throws as much as possible.
I would consider turning your FixedBuffer into a Ring Buffer also known as a Circular Buffer This way your queue won’t run out of space just because it reaches the end.
This is how I would set out the interface by basing it on Queue.
This way you can mentally, if not in code, replace
Queue<Character>withCharQueueAs the documentation notes,offeris preferable toaddand you might want to choose one of these depending on your requirements.