Java 捕获IndexOutOfBoundsException异常
我正在尝试在catch块中捕获弥补的IndexOutOfBoundsException错误。但每次它返回-1并且没有进入捕捉区 请问为什么会这样?我想伸手去抓布洛克Java 捕获IndexOutOfBoundsException异常,java,Java,我正在尝试在catch块中捕获弥补的IndexOutOfBoundsException错误。但每次它返回-1并且没有进入捕捉区 请问为什么会这样?我想伸手去抓布洛克 public class Mars { public int Setname(String Input) { int output = 0; try { output = Input.indexOf("L"); System.out
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块中编写IndexOutOfBoundsException e
时,它创建了IndexOutOfBoundsException
类的一个实例?我说得对吗
那么为什么我们不能像下面这样写呢?这可能是一个非常愚蠢的问题,但只是出于好奇,我想知道
catch(IndexOutOfBoundsException e = new IndexOutOfBoundsException())
使用
if
语句并引发异常
if(output == -1){
throw new IndexOutOfBoundsException()
}
字符串的方法indexOf()
不会引发任何异常。事实上,如果您要查找的字符不在字符串中,它将返回-1
你可以查一下
如果需要抛出异常,则必须执行类似建议的操作字符串的indexOf()
方法返回指定字符第一次出现时该字符串内的索引,如果该字符没有出现,则返回-1
。在您的情况下,您的角色不会出现,这就是为什么您会得到-1
因此,您应该做的是像这样强制执行该异常:
if(output == -1){
throw new IndexOutOfBoundsException()
}
首先,穆罕默德说本穆萨的回答是正确的 其次
IndexOutOfBoundsException e
这不会创建实例。如果抛出,它只是一个指向IndexOutOfBoundsException对象的引用。就像您在调用方法时传递的参数一样。当我们在catch块中编写IndexOutOfBoundsException e时,它正在创建IndexOutOfBoundsException类的实例?对吗?否,异常由try块中的代码引发。这是在catch中,因为您说:“我知道这段代码可以引发这种类型的异常”catch(IndexOutOfBoundsException e=new IndexOutOfBoundsException())您并没有试图创建异常,您只想处理引发的异常,所以这在逻辑上是正确的incorrect@Stultuske,请在Ayush Goyal答案中查看我的评论。。!!因此,您的意思是代码中生成的错误是IndexOutOfBoundsException类型的对象,我们使用“IndexOutOfBoundsException e”引用指向该对象。正确吗?不完全正确,异常被传递到catch块,这与将参数传递给method的方式有些相同。当编译器发现异常时,它尝试查找exeption代码的类型,而不是抛出该exeption的对象,如how throw关键字throw,但它是由jvm执行的。而不是运行相对catch块。如果有多个catch块,请将其视为方法重载。如果未找到相对catch块,请尝试父异常catch块。它不起作用。Ayo。。!!请检查我的更新代码@Javastudent刚刚尝试过,它正在输入catch块您的示例将不会输入catch块,因为
London
中有一个L
。使用不可能堆叠的东西,例如O.Setname(“堆叠”)代码>