【问题标题】:Why the exception is not getting thrown? [duplicate]为什么没有抛出异常? [复制]
【发布时间】: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 异常处理的工作原理之外,这并没有太大的目的。

标签: java throw


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 这是一个很好的问题答案,但仍然是一个不明智的方法,因为它会破坏有用的信息。最好是抛出一个新的(可能是自定义的)异常,并将原始异常作为“原因”。
    • 您好,感谢您的回答,但我只是在尝试使用 throwthrows 并希望仅通过这两个来实现这一点,我知道这是不可能的。感谢您的回答。
    • 如果使用try catch,您可以检查索引为3的元素是否适合列表,如果不适合则抛出异常:int index=3; if (index<0||index>a.size()-1) throw new IndexOutOfBoundsException("sorry");@Saurav Shrivastav
    • 因为 IndexOutOfBoundsException 是 RuntimeException 并且不是检查异常,所以不需要 throws 语句@Saurav Shrivastav
    猜你喜欢
    • 2011-12-12
    • 2016-05-10
    • 1970-01-01
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 2010-12-09
    • 2011-01-04
    • 1970-01-01
    相关资源
    最近更新 更多