2

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.
}
gemart
  • 346
  • 1
  • 3
  • 18

5 Answers5

3

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...
}
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
2

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
}
Owen
  • 36
  • 2
0

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).

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
0

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();
}
Cardinal System
  • 2,749
  • 3
  • 21
  • 42
0

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...
}
Community
  • 1
  • 1
David Jeske
  • 2,306
  • 24
  • 29