我有一个返回ArrayList类型的方法,但是我有一个try/ does /catch块,它执行异常处理。如果失败,我想返回一个字符串,表示它失败了。
这里的代码示例
public ArrayList<test> testing
{
try
{
Arraylist<test> arr = new ArrayList();
return arr
} catch (exception e) {
return "Failed";
}
}以上只是我想做的例子。想要的是,当它成功的时候,它将返回ArrayList,这是好的。但是当失败时,它将返回一个字符串。我该怎么做呢?有可能吗?
发布于 2013-12-15 05:02:15
不,您的想法似乎不合理,而且实际上是不可能的,因为毕竟,方法只能和只能返回一种类型的。您应该考虑抛出一个异常(我的偏好),或者返回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;
}https://stackoverflow.com/questions/20591366
复制相似问题