我有以下方法来实现一个ArrayList,但我不知道如何去处理异常。如果ArrayList为空,它是否会自动抛出异常,或者是否需要在方法中写入某些内容?在java中的方法声明中的异常
public T removeLast() throws EmptyCollectionException
{
//TODO: Implement this.
}
我有以下方法来实现一个ArrayList,但我不知道如何去处理异常。如果ArrayList为空,它是否会自动抛出异常,或者是否需要在方法中写入某些内容?在java中的方法声明中的异常
public T removeLast() throws EmptyCollectionException
{
//TODO: Implement this.
}
异常是延伸可抛出的对象。 你会写自己
if(list.isEmpty()){
throw new EmptyCollectionException("possibly a message here");
} else {
//your logic here to return a T
}
你需要抛出异常自己如果ArrayList
是空的。
方法签名的throws EmptyCollectionExceptio
条款只是提醒一下,调用代码,即removeLast()
可能会抛出异常(并应妥善处理)。
EmptyCollectionException不是现有的异常。定义一个新的异常:
if(list.IsEmpty()){
throw new EmptyCollectionException("message");
}
或使用IndexOutOfBoundsException异常相反,你也可以使用一个try catch
块:
try{
//Whatever could cause the exception
}catch(IndexOutOfBoundsException e){
//Handle the exception
//e.printStackTrace();
}
找到我在JDK中的EmptyCollectionException。它怎么会扔它? http://docs.oracle.com/javase/7/docs/api – ControlAltDel
@ControlAltDel使用IndexOutOfBoundsException –
您没有在方法填补,所以我们不能肯定地说。如果你使用ArrayList.remove(0);在一个空的列表,它会给你一个IndexOutOfBoundsException
在任何情况下,它永远不会抛出你的自定义异常:你需要自己抛出这个。您可以在方法的顶部执行此操作,如
public T removeLast() throws EmptyCollectionException
{
if (myList.size() == 0) throw new EmptyCollectionException("List Is Empty");
... //otherwise...
}
首先,你需要define your custom exception。这可能是:
public class EmptyCollectionExceptionextends Exception {
public EmptyCollectionException(String message) {
super(message);
}
}
然后,您可以抛出异常,因为在发布的其他答案。
public T removeLast() throws EmptyCollectionException
{
if (myList.size() == 0) throw new EmptyCollectionException("List Is Empty");
... //otherwise...
}
正确,但'else'很愚蠢;-)请参阅ControlAltDel答案以获得更好的选择。 –