我有以下方法来实现 ArrayList,但我不确定如何处理异常。如果 ArrayList 为空,它会自动抛出该异常还是我需要在方法中编写一些内容?
public T removeLast() throws EmptyCollectionException
{
//TODO: Implement this.
}
最佳答案
您还没有填写方法,所以我们不能确定。如果您使用 ArrayList.remove(0);在空列表上,它会给你一个 IndexOutOfBoundsException
无论如何,它永远不会抛出您的自定义异常:您需要自己抛出它。您可以在方法的顶部执行此操作,例如
public T removeLast() throws EmptyCollectionException
{
if (myList.size() == 0) throw new EmptyCollectionException("List Is Empty");
... //otherwise...
}
关于java - java中方法声明的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43550695/