java抛出自定义异常(如果为循环)
public class StringArray {
private String strArr[];
public StringArray(int capacity) {
strArr = new String [capacity];
}
public int indexOf(String s) throws StringNotFoundException {
for(int i=0;i<strArr.length ;++i) {
if (strArr[i].equals(s)) {
return i;
} else {
throw new StringNotFoundException();
}
}
}
}
如果字符串在数组中,我要做的是返回它的索引,否则抛出异常
但是Eclipse说我必须返回一个int
那么,我应该将返回类型更改为void还是有其他选项
StringNotFoundException是我编写的自定义异常
# 1 楼答案
那么:
避免完全使用异常
# 2 楼答案
试试这个
你为什么要这么做
# 3 楼答案
你喜欢这样吗
# 4 楼答案
为什么在这里返回-1?代码如下:
# 5 楼答案
您需要遍历数组中的每个字符串,只有当没有匹配的字符串时,才会抛出异常
我想这就是你想要的:
# 6 楼答案
你没有找到你正在寻找的
String
这一事实不足以证明使用Exception
是正确的。这不是一个例外情况,你知道它会发生,你在你的代码中这样说您的代码应该反映这一点。您不应该返回自定义值,这意味着为
-1
之类的东西添加了意义,这是不正确的有关此主题的更多信息:Should a retrieval method return 'null' or throw an exception when it can't produce the return value?