这是我的代码:
public E get(int index)
{
LLNode<E> current = head;
try {
for (int i = 0; i <= index; i++) {
if (current != null) {
current = current.next;
}
}
return current.data;
} catch (IndexOutOfBoundsException e) {
throw e;
} catch (NullPointerException e) {
// How do I handle this?
}
}
当我必须返回 E 类型的内容时,如何处理 NullPointerException
?我正在使用 JUtil 测试我的代码。我是初学者,发现这部分很难理解,请帮忙。
编辑:我正在使用 JUtil 函数测试此函数,其(部分)代码如下:
// Test empty list, get() should throw an exception
try {
emptyList.get(0);
fail("Check out of bounds");
} catch (Exception e) {
}
这里的emptylist是一个从个人创建的LinkedList类创建的空列表对象。我该如何解决这个问题(//测试空列表,get应该抛出异常),因为在这种情况下最前面提到的get函数返回NullPointerException?请帮助我。
新代码:
public E get(int index)
{
// TODO: Implement this method.
LLNode<E> current = head;
for(int i=0; i<=index; i++)
{
if(current != null)
{
current = current.next;
}
else
{
throw new IndexOutOfBoundsException();
}
}
return current.data;
}
最佳答案
您可能希望在此处抛出 IndexOutOfBoundsException
而不是捕获它。
有一些明确的理由:
- 您的代码不应该抛出任何
NullPointerException
,因为唯一可能实际发生这种情况的地方是current == null
,最理想的是当您想要抛出IndexOutOfBoundsException
时。
如果不使用 try...catch
进行重写,您的代码将如下所示:
public E get(int index) {
// TODO: Implement this method.
LLNode<E> current = head;
for (int i = 0; i <= index; i++) {
if (current != null) {
current = current.next;
} else {
throw new IndexOutOfBoundsException();
}
}
return current.data;
}
关于java - 当函数必须返回通用数据类型的某些值时,在java中处理NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38596346/