0

I have code here which runs a short series of tests to see if the last element in the array is the expected number. The code that I have to put in goes where [???] is currently.

   //The answer must be the shortest possible
class EmptyArrayException extends RuntimeException{}
class ArrayUtil{
  public static Object lastElement (Object[]array)[???]{
    if(array.length>0)return array[array.length-1];
    throw new EmptyArrayException();
  }
}
public class Exercise{
  public static void test(){
    assert ArrayUtil.lastElement(new Integer[]{1,2,3}).equals(3);
    assert ArrayUtil.lastElement(new Integer[]{1,2}).equals(2);
    assert ArrayUtil.lastElement(new Integer[]{1}).equals(1);
    assert ArrayUtil.lastElement(new Integer[]{}).equals(1);
    assert false:"Code not reachable";
  }
  public static void main(String [] arg){
    try{ test();}
    catch(Throwable t){/*the test suit
      logs t on the test results: 
      a single place for error logging.*/}
  }
}

I assume that I would write ' throws EmptyArrayException ', but this is wrong. ' throws EmptyArrayException() ' is wrong too.

So what do I put in the [???] space?

  • 1
    If an exception type is a subtype of `RuntimeException`, you don't need to specify it in the `throws` clause. – Dawood ibn Kareem May 27 '14 at 20:38
  • What do you mean by wrong? Did you perhaps surrounded `throws EmptyArrayException` with `[` `]`? – Pshemo May 27 '14 at 20:39
  • `throws EmptyArrayException` is the correct syntax. What do you mean by "but this is wrong"? Are you getting a compiler error? – azurefrog May 27 '14 at 20:40
  • For the shortest possible? Nothing. You would put nothing there. If you weren't throwing a RuntimeException, you would needs a `throws` clause. – Elliott Frisch May 27 '14 at 20:40

1 Answers1

3

Since your exception is a RuntimeException you don't need to specify anything. However you can. Sometimes I do it in an effort to document that such method might throw a certain exception.

public static Object lastElement (Object[]array) throws EmptyArrayException 

It is up to you.

Claudio
  • 1,848
  • 12
  • 26