ViniciusArruda
ViniciusArruda

Reputation: 990

In this case, how should I deal with exception?

I'm new in java. I did a class that implements a FIFO. I used a LinkedList to impement it. I want to know what exception should I throw when an user of my class Fifo tries to remove an element from the list when it is empty and how to do it correctly.

import java.util.*;

class Fifo<E> 
{
    private List<E> list = new LinkedList<E>();

    public void add(E element)
    {
        list.add(element); 
    }

    public E remove() throws IllegalStateException
    {
        if(list.isEmpty()) 
            throw new IllegalStateException(); 
        else
            return list.remove(0);
    }
}

An example of using it is a restaurant that has a queue of orders.

class Restaurant
{
    static public void main(String[] args) 
    {
        Fifo<Order> f = new Fila<Order>();

        f.add(new Order("soup"));

        try
        {
            System.out.println(f.remove().toString());
            System.out.println(f.remove().toString());
        }
        catch(IllegalStateException e)
        {
            System.out.println("There is no more orders.");
        }
    }
}

It is necessary to be a RunTimeException ? In this case, the user of my class can handle with the problem, just saying to the user of the system that there is no more orders, without quitting the system.

Thanks.

Upvotes: 0

Views: 56

Answers (4)

secolive
secolive

Reputation: 589

For coherence with the rest of the Java API, I would use NoSuchElementException (in java.util).

As the caller should normally be verifying if a queue is empty before trying to pop from it, such error condition would indicate a programming error, and in such cases we commonly use RuntimeException's.

If you did use checked exceptions (i.e. not child of RuntimeException) then the caller would be forced to handle the case with a try-catch or a throws clause, for no real benefit.

Upvotes: 0

Keefe Roedersheimer
Keefe Roedersheimer

Reputation: 347

The underlying java collection uses a NoSuchElementException which is what is done in the underlying collection - in fact, you don't need to specifically throw it, it will happen by default. In general about exceptions, you should understand that this type of an exception should be unchecked - it's known at runtime only, not at compile time. A discussion of this is in the documentation here

Upvotes: 0

Kayaman
Kayaman

Reputation: 73558

You can use any kind of exception you want to, even create your own.

The built-in classes use runtime exceptions since it would be frustrating to have try/catch everywhere, and the programmer shouldn't be trying to remove elements without checking that there are elements to be removed in the first place.

Upvotes: 1

algor
algor

Reputation: 414

You can throw java.util.NoSuchElementException as it's done in Collection framework

Upvotes: 4

Related Questions