首页 > 解决方案 > 如何在抛出错误的同时返回一个空列表?

问题描述

我现在正在做作业,如果该字段为空,我被要求返回一个空列表并打印一条错误消息。

到目前为止,这是我的代码,但是抛出错误或返回空列表(如果我更改顺序,则为后一个)是无法访问的。我该怎么做?

// the method is not void it returns a list
  if (fileContent.equals(null)) {
            return Collections.emptyList();
            throw new Error("ERROR: No content loaded before parsing.");
        } else {
            // return another list ;
}

这是我得到的错误:

org.junit.ComparisonFailure: Console output not as expected in parseFileContent. 
Expected :ERROR: No content loaded before parsing.
Actual   :ERROR: executing parseFileContent for console output check:java.lang.NullPointerException

谢谢!

标签: javaerror-handling

解决方案


我猜你不需要抛出错误,而只需要打印它。在这种情况下,请执行以下操作:

if(fileContent.equals(null)) {
    // If you need to print the error:
    System.err.println("ERROR: No content loaded before parsing.");
    return Collections.EMPTY_LIST;  
} else {
    // return anotherList
}

推荐阅读