为什么没有抛出异常?

时间:2021-04-13 13:40:10

标签: java throw

下面是我的代码。当我运行它时,我在线程 "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 2 中得到 Exception 而不是我的异常消息。谁能解释一下我做错了什么或者为什么会这样? 谢谢!

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");
            
      }
}

2 个答案:

答案 0 :(得分:2)

您的异常没有被抛出,因为它之前的行正在抛出异常并结束执行。当尝试访问超出 List 大小的元素时,ArrayList 已经知道抛出 IndexOutOfBoundsException 并且因为它没有被捕获,您的程序结束并且不会继续您的 throw 语句。

答案 1 :(得分:1)

使用 try catch 块捕获此异常:

  public static void main(String[] args){
    try {
          ArrayList a = new ArrayList();
          a.add(10);
          a.add(20);
          a.get(3); //element with index 3 doesn't exists
        } catch (IndexOutOfBoundsException e) {
            throw new IndexOutOfBoundsException("sorry");
        }
  }