-1

Which type of exception is occurs in this code.
Why the catch statement is not taking ArrayOutofBoundsException e.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

public static void main(String[] args) {
    int i,j,k,n,m,l,x,y;

    Scanner sc=new Scanner (System.in);
    n=sc.nextInt();
    ArrayList [] a=new ArrayList[n];
    for(i=0;i<n;i++)
        {
        m=sc.nextInt();
       a[i]=new ArrayList();
        for(j=0;j<m;j++)
        {
            a[i].add(sc.nextInt());
        } 
    }
    k=sc.nextInt();
    for(i=0;i<k;i++)
        {
        x=sc.nextInt();
        y=sc.nextInt();
        try
            {
            System.out.println(a[x-1].get(y-1));
        }
        catch(ArrayOutofBoundsException e)
            {
            System.out.println("ERROR!");
        }
    }

  }
}

1 Answers1

2

Since you are using Array of ArrayList in your program,

From the java doc an ArrayList's get method

Throws: IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size())

and

All array accesses are checked at run time; an attempt to use an index that is less than zero or greater than or equal to the length of the array causes an ArrayIndexOutOfBoundsException to be thrown.

So you try to catch IndexOutOfBoundsException in your program along with ArrayIndexOutOfBoundsException.

Ex:

try {
    System.out.println(a[x - 1].get(y - 1));
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("ERROR!");
} catch (IndexOutOfBoundsException e) {
    System.out.println("ERROR! IndexOutOfBoundsException ");
}
Unknown
  • 2,037
  • 3
  • 30
  • 47