【发布时间】:2021-07-08 13:49:57
【问题描述】:
下面是我的代码。当我运行它时,我在线程“main”java.lang.IndexOutOfBoundsException 中收到异常:索引:3,大小:2,而不是我的异常消息。谁能解释一下我做错了什么或者为什么会这样? 谢谢!
Code
public class Main {
public static void main(String[] args) throws Exception{
ArrayList a= new ArrayList();
a.add(10);
a.add(20);
a.get(3) ;
throw new IndexOutOfBoundsException("sorry");
}
}
【问题讨论】:
-
因为
a.get(3);已经抛出异常并且代码执行在此之后停止。 -
你希望
a.get(3)做什么? -
@OHGODSPIDERS 好的,谢谢。有什么办法可以让它抛出异常以及我的价值
sorry? -
您可以在 try & catch 中添加整个块。在侧面捕获中,您可以抛出自己的 IndexOutOfBoundsException。
-
您可以捕获 IndexOutOfBoundsException 并使用您的自定义消息抛出一个新异常:
try { a.get(3); } catch (IndexOutOfBoundsException e) { throw new IndexOutOfBoundsException("sorry"); }除了试验和了解 java 异常处理的工作原理之外,这并没有太大的目的。