【发布时间】:2014-07-16 21:36:45
【问题描述】:
我在这里有代码,它运行一系列简短的测试来查看数组中的最后一个元素是否是预期的数字。我必须输入的代码位于 [???] 当前所在的位置。
//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.*/}
}
}
我假设我会写 ' throws EmptyArrayException ',但这是错误的。 ' throws EmptyArrayException() ' 也是错误的。
那么我应该在 [???] 空格中放什么?
【问题讨论】:
-
如果异常类型是
RuntimeException的子类型,则不需要在throws子句中指定。 -
你说的错是什么意思?你有没有用
[]包围throws EmptyArrayException? -
throws EmptyArrayException是正确的语法。 “但这是错误的”是什么意思?您是否遇到编译器错误? -
尽可能短?没有。你什么都不会放在那里。如果您没有抛出 RuntimeException,则需要一个
throws子句。