6

I am trying to write a fixed sized queue for generic type elements.The user can call the constructor, providing a size and an internal array is created for that size.(see below)

class FixedSizeQ<E>{
    private E[] q;
    private int N;

    public FixedSizeQ(int max) {
        super();
        q = (E[]) new Object[max];
        N = 0;
    }
..
}

I thought of defining an isEmpty() and isFull() methods and an insert() method for the above.If the client tries to add an element to the already full array,I want to throw an exception.Going through the javadocs,I thought IllegalStateException would be the correct exception to throw.

public boolean isFull(){
    return N == q.length;
}
public void insert(Item item){
    if(isFull()){
        throw new IllegalStateException("queue full");
    }
    ...     
}

I want to know if my understanding is correct..Someone suggested that IllegalArgumentException is more appropriate.Can someone advise?

damon
  • 8,127
  • 17
  • 69
  • 114
  • My first thought would als have been `IllegalStateException`. You might consider to provide more information and specify the allowed max value in the exception as well. – Devolus Aug 09 '13 at 07:04
  • [Here's a good discussion](http://stackoverflow.com/a/77361/1679863) about when to throw an exception. – Rohit Jain Aug 09 '13 at 07:08
  • I would provide two new exceptions: EmptyQueueException and FullQueueException, both extending IllegalStateException (as they are illegal states). The one is thrown at removing an object, the other at inserting. And - of course - you must provide the isFull() and isEmtpy() methods, because the caller is responsible for cheking the queue prior to remove or insert. – Seelenvirtuose Aug 09 '13 at 07:08

6 Answers6

6

I think you should make the insert method return boolean, and return true if the object was inserted and false if the queue is full. Adding objects to a full queue does not seem like an exceptional condition to me.

In any case, if no predefined exception in the Java API is a good match, you can create an exception type of your own to best suit the situation:

public class QueueFullException extends RuntimeException {
    // or "extends Exception" if you want it checked
    ...
}
Joni
  • 108,737
  • 14
  • 143
  • 193
4

Use IllegalStateException.It best suites your requirement.
By the definition of java docs.

IllegalStateException Signals that a method has been invoked at an illegal or inappropriate time.

According to IllegalArgumentException won't suits your requirement.Its definition in java docs says.

Thrown to indicate that a method has been passed an illegal or inappropriate argument

Example in API is boolean add(E e) method of java.util.Queue.

add() throws IllegalStateException - if the element cannot be added at this time due to capacity restrictions

Prabhaker A
  • 8,317
  • 1
  • 18
  • 24
3

There are four scenarios when your queue is full

  1. return false/true indicating a put attempt is successful or not
  2. throw an exception
  3. block till queue is full optionally define timeout
  4. return or throw exception after waiting for specified amount of time.
  5. Define different methods which incorporates the above scenarios individually. for example add and offer method in BlockingQueue.

You should either use Bounded BlockingQueue or see the implementation of it.

and yes IllegalStateException would be more appropriate.

as it is also being used in ArrayBlockingQueue implementation

/**
 * Inserts the specified element at the tail of this queue if it is
 * possible to do so immediately without exceeding the queue's capacity,
 * returning <tt>true</tt> upon success and throwing an
 * <tt>IllegalStateException</tt> if this queue is full.
 *
 * @param e the element to add
 * @return <tt>true</tt> (as specified by {@link Collection#add})
 * @throws IllegalStateException if this queue is full
 * @throws NullPointerException if the specified element is null
 */
public boolean add(E e) {
veritas
  • 2,444
  • 1
  • 21
  • 30
2

You throw IllegalStateException when the defined the internal properties of something wrong and therefore it cannot work further.
You throw an IllegalArgumentException when the user made a mistake in parametrizing the object.
In my opinion, I would choose IllegalStateException because the other one might suggest that the element that was tried to be pushed into the queue is of wrong type.
According to Javadoc: IllegalStateException signals that a method has been invoked at an illegal or inappropriate time. In other words, the Java environment or Java application is not in an appropriate state for the requested operation.
While, IllegalArgumentException is thrown to indicate that a method has been passed an illegal or inappropriate argument.

Levente Kurusa
  • 1,858
  • 14
  • 18
0

Just try your own, u can create new exception by extending Exception class

class NoSpaceToInsert extends Exception
    {
        String message;
        int code;

        public NoSpaceToInsert(int errorCode, String errorMessage)
        {
            message = errorMessage;
            code = errorCode;
        }

        public String toString()
        {
            return "ErrorCode" + code + "ErrorMessage" + message;

        }
    }

now throw

throw new NoSpaceToInsert(errorCode, errorMessage);
Selvaraj
  • 714
  • 2
  • 6
  • 14
-1

According to List, when you set a value out of bond, it throws an IndexOutOfBoundsException.

    @throws IndexOutOfBoundsException if the index is out of range
    E set(int index, E element);
criszhao
  • 134
  • 6