gemart
gemart

Reputation: 376

Exceptions in method declaration in java

I have the following method to implement for an ArrayList, but I'm not sure how to go about treating the exception. If the ArrayList is empty does it automatically throw that exception or do I need to write something in the method?

public T removeLast() throws EmptyCollectionException
{
    //TODO: Implement this.
}

Upvotes: 2

Views: 856

Answers (5)

David Jeske
David Jeske

Reputation: 2466

First, you need to define your custom exception. That might be:

public class EmptyCollectionExceptionextends Exception {
    public EmptyCollectionException(String message) {
        super(message);
    }
}

Then you can throw the exception as in some of the other answers posted.

public T removeLast() throws EmptyCollectionException
{
  if (myList.size() == 0) throw new EmptyCollectionException("List Is Empty");
  ... //otherwise...
}

Upvotes: 0

Cardinal System
Cardinal System

Reputation: 3422

EmptyCollectionException is not an existing exception. Define a new exception:

if(list.IsEmpty()){
throw new EmptyCollectionException("message");
}

or use IndexOutOfBoundsException instead, you can also use a try catch block:

try{

   //Whatever could cause the exception

}catch(IndexOutOfBoundsException e){
   //Handle the exception
   //e.printStackTrace();
}

Upvotes: 0

ControlAltDel
ControlAltDel

Reputation: 35011

You haven't filled in the method, so we can't say for sure. If you used ArrayList.remove(0); on an empty list, it would give you a IndexOutOfBoundsException

In any case, it's never going to throw your custom exception: You need to throw this yourself. You can do this at the top of the method, like

public T removeLast() throws EmptyCollectionException
{
  if (myList.size() == 0) throw new EmptyCollectionException("List Is Empty");
  ... //otherwise...
}

Upvotes: 3

Owen
Owen

Reputation: 36

An exception is an object that extends throwable. You would write that yourself

if(list.isEmpty()){
    throw new EmptyCollectionException("possibly a message here");
} else {
    //your logic here to return a T
}

Upvotes: 2

Paulo Mattos
Paulo Mattos

Reputation: 19339

You need to throw the exception yourself if the ArrayList is empty.

The throws EmptyCollectionExceptio clause in the method signature is only a reminder, for the calling code, that removeLast() might throw an exception (and should be properly handled).

Upvotes: 0

Related Questions