【问题标题】:How to return a string while my method is returning ArrayList?当我的方法返回 ArrayList 时如何返回字符串?
【发布时间】:2013-12-15 05:00:12
【问题描述】:

我有一个返回 ArrayList 类型的方法,但我有一个执行异常处理的 try/throw/catch 块。如果失败,我想返回一个表示失败的字符串。

这里是我的代码示例

public ArrayList<test> testing
{
    try
    {
        Arraylist<test> arr = new ArrayList();
        return arr

    } catch (exception e) {
           return "Failed";
    }
}

以上只是我想做的例子。想要的是当它成功时,它会返回没问题的 ArrayList。但是当失败时,它会返回一个字符串。我该怎么做?有可能吗?

【问题讨论】:

  • 不,这是不可能的。 Java 是一种强类型语言。由于您声明您的方法返回ArrayList,因此您必须只返回那个或null
  • 你到底想用你的代码完成什么?

标签: java arraylist return-value


【解决方案1】:

不,您的想法似乎不合理,实际上是不可能的,因为毕竟一个方法只能并且应该只返回一个单一类型。您应该考虑抛出异常(我的偏好),或返回 null 作为标记(我认为它不太好,因为它提供的信息较少)。

即,

public ArrayList<test> testing throws SomeException {
    Arraylist<test> arr = new ArrayList();
    if (somethingFails) { 
      String message = "an explanation of why the method failed";
      throw new SomeException(message);
    }
    return arr;
}

【讨论】:

    【解决方案2】:

    您应该做的是throw您自己的异常类型,而不是尝试在发生异常时返回字符串,这表明发生了故障(google how to create custom exceptions)。调用此方法的任何内容都需要包含在其自己的 try-catch 块中,并首先通过 catch 过滤您的自定义异常。如果该 catch 块触发,您就知道发生了故障。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-03
      • 2014-03-14
      • 1970-01-01
      • 1970-01-01
      • 2018-05-24
      • 2014-08-19
      • 2012-02-05
      • 2020-04-13
      相关资源
      最近更新 更多