Search code examples
javathrow

Why the exception is not getting thrown?


Below is my code. When i am running it I am getting Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 2 and not my Exception message. Can anyone please explain me what I am doing wrong or why is this happening? Thanks!

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

Solution

  • Your exception is not being thrown because the line before it is throwing the exception and ending execution. The ArrayList already knows to throw an IndexOutOfBoundsException when trying to access an element beyond the size of the List and because it is not caught, your program ends and does not continue to your throw statement.