我正在 try catch catch block 中的 IndexOutOfBoundsException 错误。但每次它返回-1并且不进入catch block
请问为什么会这样?我想伸手捕获方 block 。
public class Mars {
public int Setname(String Input) {
int output = 0;
try {
output = Input.indexOf("L");
System.out.println("Error:" + Input.indexOf("L"));
if (output == -1){
throw new IndexOutOfBoundsException();
}
}
catch (IndexOutOfBoundsException e) {
System.out.println("Error:2" + e.getStackTrace());
}
return output;
}
public static void main(String[] args) {
Mars O = new Mars();
O.Setname("London");
}
}
第二件事是:当我们在 catch block 中编写 IndexOutOfBoundsException e
时,它会创建 IndexOutOfBoundsException
类的实例?我说得对吗?
那么为什么我们不能像下面这样写呢?这可能是一个非常愚蠢的问题,但出于好奇我想知道。
catch(IndexOutOfBoundsException e = new IndexOutOfBoundsException())
最佳答案
String 的 indexOf()
方法返回此字符串中指定字符第一次出现的索引,如果该字符未出现,则返回 -1
。在您的情况下,您的角色不会出现,这就是您得到 -1
的原因。
所以你应该做的是像这样强制该异常:
if(output == -1){
throw new IndexOutOfBoundsException()
}
关于java - 捕获 IndexOutOfBoundsException 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47261457/