java - 如何抛出错误并同时返回空列表?

标签 java error-handling

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

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

// 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

谢谢!

最佳答案

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

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
}

关于java - 如何抛出错误并同时返回空列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60875004/

相关文章:

java soap webservice xml到对象

php - Cakephp不明索引问题

c# - 使用BackGroundWorker的错误处理条件失败

javascript - 在使用angular,angularjs和jQuery技术构建的应用程序中,处理客户端全局错误的最佳和最佳方法是什么?

php - 在MVC中处理错误/异常

java - 如何防止弹出基本身份验证表单

java - 从代码访问XML枚举值

java - 使用 dagger2 进行依赖注入(inject)时,我可以只注入(inject)父类(super class)吗?

ajax - 客户端 AJAX 调用错误的一般处理

java - 我们如何在两个 war 文件之间访问相同的缓存?