【问题标题】:How to write exceptions (class x throws y) [duplicate]如何编写异常(类x抛出y)[重复]
【发布时间】: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 子句。

标签: java exception throws


【解决方案1】:

由于您的例外是RuntimeException,因此您无需指定任何内容。不过你可以。有时我这样做是为了证明这种方法可能会引发某种异常。

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

这取决于你。

【讨论】:

  • 为什么答案几乎总是很简单?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多